protected override object?GetExportedValueCore()
                {
                    if (_export == null)
                    {
                        CompositionContainer?childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog);

                        Debug.Assert(childContainer.CatalogExportProvider != null);
                        Export?export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any);
                        lock (_lock)
                        {
                            if (_export == null)
                            {
                                _childContainer = childContainer;
                                Thread.MemoryBarrier();
                                _export = export;

                                childContainer = null;
                                export         = null;
                            }
                        }
                        childContainer?.Dispose();
                    }

                    return(_export.Value);
                }
Exemplo n.º 2
0
        public void Execute()
        {
            //
            // カタログ構築.
            //  AggregateCatalogは、複数のCatalogを一つにまとめる役割を持つ。
            //
            var catalog = new AggregateCatalog();
            // AssemblyCatalogを利用して、自分自身のアセンブリをカタログに追加.
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(MEFSamples01).Assembly));

            //
            // コンテナを構築.
            //
            _container = new CompositionContainer(catalog);
            try
            {
                // 合成実行.
                _container.ComposeParts(this);

                // 実行.
                Output.WriteLine(_exporter.Name);
            }
            catch (CompositionException ex)
            {
                // 合成に失敗した場合.
                Output.WriteLine(ex.ToString());
            }

            if (_container != null)
            {
                _container.Dispose();
            }
        }
Exemplo n.º 3
0
        static void Main() 
        {
            // important to call these before creating application host
            Application.EnableVisualStyles();
            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());

            // Create a catalog with all the components that make up the application, except for
            //  our MainForm.
            var catalog = new TypeCatalog(
                typeof(SettingsService),                // persistent settings and user preferences dialog
                typeof(CommandService),                 // handles commands in menus and toolbars
                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(StandardFileExitCommand),        // standard File exit menu command
                typeof(HelpAboutCommand),               // Help -> About command
                typeof(FolderViewer),                   // manages TreeControl to display folder hierarchy
                typeof(FileViewer),                     // managed ListView to display last selected folder contents

                typeof(NameDataExtension),              // extension to display file name
                typeof(SizeDataExtension),              // extension to display file size
                typeof(CreationTimeDataExtension),      // extension to display file creation time

                typeof(UserFeedbackService),            // component to send feedback form to SHIP
                typeof(VersionUpdateService),           // component to update to latest version on SHIP

                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );          

            var container = new CompositionContainer(catalog);

            // manually add the MainForm
            var batch = new CompositionBatch();
            var mainForm = new MainForm
            {
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };
            // our custom main Form with SplitContainer
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-File-Explorer-Sample".Localize()));
            container.Compose(batch);

            // initialize all components which require it
            container.InitializeAll();
            
            Application.Run(mainForm);

            container.Dispose();
        }
Exemplo n.º 4
0
        public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer()
        {
            var container = new CompositionContainer();
            var disposablePart = new AnyPartDisposable();
            var batch = new CompositionBatch();
            batch.AddPart(batch);
            container.Compose(batch);

            container.Dispose();
            Assert.IsFalse(disposablePart.IsDisposed);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);
            for (int i = 0; i < 3; i++)
                container.GetExportedValue<NonSharedPlugin>().Run();
            for (int i = 0; i < 3; i++)
                container.GetExportedValue<SharedPlugin>().Run();
            for (int i = 0; i < 3; i++)
                container.GetExportedValue<AnyPlugin>().Run();
            container.GetExportedValue<TesterAny>().Test();
            container.GetExportedValue<TesterShared>().Test();
            container.GetExportedValue<TesterNonShared>().Test();

            container.Dispose();
        }
        public void CanBeCollectedAfterDispose()
        {
            AggregateExportProvider exportProvider = new AggregateExportProvider();
            var catalog = new AggregateCatalog(CatalogFactory.CreateDefaultAttributed());
            var container = new CompositionContainer(catalog, exportProvider);

            WeakReference weakContainer = new WeakReference(container);
            container.Dispose();
            container = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.IsFalse(weakContainer.IsAlive);

            GC.KeepAlive(exportProvider);
            GC.KeepAlive(catalog);
        }
                public void Dispose()
                {
                    CompositionContainer?childContainer = null;
                    Export?export;

                    if (_export != null)
                    {
                        lock (_lock)
                        {
                            export         = _export;
                            childContainer = _childContainer;

                            _childContainer = null;
                            Thread.MemoryBarrier();
                            _export = null;
                        }
                    }

                    childContainer?.Dispose();
                }
Exemplo n.º 8
0
        /// <summary>
        ///     This method can be used to initialize the global container used by <see cref="CompositionInitializer.SatisfyImports(object)"/>
        ///     in case where the default container doesn't provide enough flexibility. 
        ///     
        ///     If this method is needed it should be called exactly once and as early as possible in the application host. It will need
        ///     to be called before the first call to <see cref="CompositionInitializer.SatisfyImports(object)"/>
        /// </summary>
        /// <param name="catalogs">
        ///     An array of <see cref="ComposablePartCatalog"/> that should be used to initialize the <see cref="CompositionContainer"/> with.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="catalogs"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///     Either <see cref="Initialize(CompositionContainer)" /> or <see cref="Initialize(ComposablePartCatalog[])" />has already been called or someone has already made use of the global 
        ///     container via <see cref="CompositionInitializer.SatisfyImports(object)"/>. In either case you need to ensure that it 
        ///     is called only once and that it is called early in the application host startup code.
        /// </exception>
        public static CompositionContainer Initialize(params ComposablePartCatalog[] catalogs)
        {
            AggregateCatalog aggregateCatalog = new AggregateCatalog(catalogs);
            CompositionContainer container = new CompositionContainer(aggregateCatalog);
            try
            {
                CompositionHost.Initialize(container);
            }
            catch
            {
                container.Dispose();

                // NOTE : this is important, as this prevents the disposal of the catalogs passed as input arguments
                aggregateCatalog.Catalogs.Clear();
                aggregateCatalog.Dispose();

                throw;
            }

            return container;
        }
Exemplo n.º 9
0
        /// <summary>
        ///     This method can be used to initialize the global container used by <see cref="CompositionInitializer.SatisfyImports(object)"/>
        ///     in case where the default container doesn't provide enough flexibility.
        ///
        ///     If this method is needed it should be called exactly once and as early as possible in the application host. It will need
        ///     to be called before the first call to <see cref="CompositionInitializer.SatisfyImports(object)"/>
        /// </summary>
        /// <param name="catalogs">
        ///     An array of <see cref="ComposablePartCatalog"/> that should be used to initialize the <see cref="CompositionContainer"/> with.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="catalogs"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///     Either <see cref="Initialize(CompositionContainer)" /> or <see cref="Initialize(ComposablePartCatalog[])" />has already been called or someone has already made use of the global
        ///     container via <see cref="CompositionInitializer.SatisfyImports(object)"/>. In either case you need to ensure that it
        ///     is called only once and that it is called early in the application host startup code.
        /// </exception>
        public static CompositionContainer Initialize(params ComposablePartCatalog[] catalogs)
        {
            AggregateCatalog     aggregateCatalog = new AggregateCatalog(catalogs);
            CompositionContainer container        = new CompositionContainer(aggregateCatalog);

            try
            {
                CompositionHost.Initialize(container);
            }
            catch
            {
                container.Dispose();

                // NOTE : this is important, as this prevents the disposal of the catalogs passed as input arguments
                aggregateCatalog.Catalogs.Clear();
                aggregateCatalog.Dispose();

                throw;
            }

            return(container);
        }
                public void Dispose()
                {
                    CompositionContainer childContainer = null;
                    Export export = null;

                    if (this._export != null)
                    {
                        lock (this._lock)
                        {
                            export         = this._export;
                            childContainer = this._childContainer;

                            this._childContainer = null;
                            Thread.MemoryBarrier();
                            this._export = null;
                        }
                    }

                    if (childContainer != null)
                    {
                        childContainer.Dispose();
                    }
                }
Exemplo n.º 11
0
        public void DisposeContainerDisposesTransientParsley()
        {
            var catalog = new TypeCatalog(typeof(Ploeh.Samples.Menu.Mef.Attributed.Lifetime.NonShared.Parsley));
            var container = new CompositionContainer(catalog);

            var ingredient = container.GetExportedValue<IIngredient>();

            container.Dispose();

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.True(parsley.IsDisposed);
        }
Exemplo n.º 12
0
        private void Compose()
        {
            _logger.Info("Adapter Service is looking for a plugin");
            CompositionContainer container = null;

            try
            {
                string codebase = AppDomain.CurrentDomain.BaseDirectory;

                var pluginAssembly = ConfigurationManager.AppSettings["pluginAssembly"];
                var catalog = new SafeDirectoryCatalog(codebase, pluginAssembly);
                container = new CompositionContainer(catalog);
                container.ComposeParts(this);
            }
            catch (CompositionException ex)
            {
                foreach (var error in ex.Errors)
                {
                    _logger.Fatal("Error when loading plugin", error.Exception);
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                foreach (var error in ex.LoaderExceptions)
                {
                    _logger.Fatal("Error when searching for plugin", error);
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal("Error when loading plugin", ex);
            }
            finally
            {
                if (container != null)
                {
                    container.Dispose();
                }
            }
        }
Exemplo n.º 13
0
		static void  Main()
        {

#if DEBUG
            AllocConsole();
#endif

            // It's important to call these before starting the app; otherwise theming and bitmaps
            //  may not render correctly.
            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());

#if !DEBUG
            SplashForm.ShowForm(typeof(LevelEditorApplication), "LevelEditor.Resources.SplashImg.png");
#endif
          
            // Register the embedded image resources so that they will be available for all users of ResourceUtil,
            //  such as the PaletteService.
            ResourceUtil.Register(typeof(Resources));

            // enable metadata driven property editing
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Add selected ATF components.
            TypeCatalog AtfCatalog = new TypeCatalog(       
                typeof(SettingsService),                // persistent settings and user preferences dialog               
                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(CommandService),                 // menus and toolbars
                typeof(ControlHostService),             // docking control host                        
                typeof(AtfUsageLogger),                 // logs computer info to an ATF server
                typeof(CrashLogger),                    // logs unhandled exceptions to an ATF server
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),
                typeof(AtfScriptVariables),
                typeof(AutomationService),
                typeof(FileDialogService),              // standard Windows file dialogs
                typeof(DocumentRegistry),               // central document registry with change notification            
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup            
                typeof(StandardFileExitCommand),        // standard File exit menu command            
                typeof(StandardViewCommands),           // standard View commands: frame selection, frame all
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title            
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                typeof(StandardLockCommands),           // standard Edit menu lock/unlock commands            
                typeof(PaletteService),                 // global palette, for drag/drop instancing            
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor             
                typeof(PropertyEditor),
                typeof(GridPropertyEditor),                
                typeof(WindowLayoutService),            // multiple window layout support
                typeof(WindowLayoutServiceCommands),    // window layout commands
                typeof(HistoryLister),                  // visual undo/redo
                typeof(SkinService),
                typeof(ResourceService)
                );

            TypeCatalog LECoreCatalog = new TypeCatalog(                
                typeof(LevelEditorCore.ImageThumbnailResolver),
                typeof(LevelEditorCore.DesignViewSettings),
                typeof(LevelEditorCore.ResourceLister),
                typeof(LevelEditorCore.ThumbnailService),
                typeof(LevelEditorCore.ResourceMetadataEditor),
                typeof(LevelEditorCore.LayerLister),
                typeof(LevelEditorCore.ResourceConverterService),
                typeof(LevelEditorCore.RenderLoopService),                
                typeof(LevelEditorCore.Commands.PickFilterCommands),
                typeof(LevelEditorCore.Commands.DesignViewCommands),
                typeof(LevelEditorCore.Commands.ManipulatorCommands),
                typeof(LevelEditorCore.Commands.ShowCommands),
                typeof(LevelEditorCore.Commands.GroupCommands),
                typeof(LevelEditorCore.Commands.CameraCommands)
                );

            TypeCatalog thisAssemCatalog = new TypeCatalog(                
                typeof(LevelEditor.GameEditor),
                typeof(LevelEditor.BookmarkLister),                                
                typeof(LevelEditor.GameDocumentRegistry),                
                typeof(LevelEditor.SchemaLoader),
                typeof(LevelEditor.PrototypingService),
                typeof(LevelEditor.PrefabService),
                typeof(LevelEditor.GameProjectLister),
                typeof(LevelEditor.ResourceMetadataService),
                typeof(LevelEditor.ResourceConverter),               
                typeof(LevelEditor.Terrain.TerrainEditor),
                typeof(LevelEditor.Terrain.TerrainManipulator),                 
                typeof(LevelEditor.SnapFilter),
                typeof(LevelEditor.PickFilters.LocatorPickFilter),
                typeof(LevelEditor.PickFilters.BasicShapePickFilter),
                typeof(LevelEditor.PickFilters.NoCubePickFilter),                
                typeof(LevelEditor.Commands.PaletteCommands),
                typeof(LevelEditor.Commands.LevelEditorFileCommands),
                typeof(LevelEditor.Commands.HelpAboutCommand),
                typeof(LevelEditor.Commands.LevelEditorCommands),
                typeof(LevelEditor.Commands.LayeringCommands),
                typeof(LevelEditor.Commands.PivotCommands)
                // To use Open Sound Control (OSC), enable these three components:
                //,
                //typeof(LevelEditor.OSC.OscClient),
                //typeof(OscCommands),                    // Provides a GUI for configuring OSC support and to diagnose problems.
                //typeof(OscCommandReceiver)              // Executes this app's commands in response to receiving matching OSC messages.
                                                        // Needs to come after all the other ICommandClients in the catalog.
                );

            TypeCatalog renderingInteropCatalog = new TypeCatalog(
                typeof(RenderingInterop.NativeGameEditor),
                typeof(RenderingInterop.ThumbnailResolver),
                typeof(RenderingInterop.RenderCommands),
                typeof(RenderingInterop.AssetResolver),
                typeof(RenderingInterop.NativeDesignView),
                typeof(RenderingInterop.ResourcePreview),
                typeof(RenderingInterop.TranslateManipulator),  
                typeof(RenderingInterop.ExtensionManipulator),
                typeof(RenderingInterop.ScaleManipulator),
                typeof(RenderingInterop.RotateManipulator),
                typeof(RenderingInterop.TranslatePivotManipulator),
                typeof(RenderingInterop.TextureThumbnailResolver)
                );


            List<ComposablePartCatalog> catalogs = new List<ComposablePartCatalog>();
            catalogs.Add(AtfCatalog);
            catalogs.Add(LECoreCatalog);
            catalogs.Add(renderingInteropCatalog);
            catalogs.Add(thisAssemCatalog);
            
                        
            // temp solution, look for statemachine plugin by name.
            string pluginDir = Application.StartupPath;
            string stmPlg = pluginDir + "\\StateMachinePlugin.dll";
            if(File.Exists(stmPlg))
            {
                Assembly stmPlgAssem = Assembly.LoadFrom(stmPlg);
                catalogs.Add(new AssemblyCatalog(stmPlgAssem));
            }

            
            AggregateCatalog catalog = new AggregateCatalog(catalogs);
               
                      
            // Initialize ToolStripContainer container and MainForm
            ToolStripContainer toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;
            MainForm mainForm = new MainForm(toolStripContainer);
            mainForm.Text = "LevelEditor".Localize("the name of this application, on the title bar");
             
            CompositionContainer container = new CompositionContainer(catalog);
            CompositionBatch batch = new CompositionBatch();
            AttributedModelServices.AddPart(batch, mainForm);
            container.Compose(batch);

            LevelEditorCore.Globals.InitializeComponents(container);
            // Initialize components 
            
            foreach (IInitializable initializable in container.GetExportedValues<IInitializable>())
                initializable.Initialize();           

            AutoDocumentService autoDocument = container.GetExportedValue<AutoDocumentService>();
            autoDocument.AutoLoadDocuments = false;
            autoDocument.AutoNewDocument = true;
            mainForm.Shown += delegate { SplashForm.CloseForm(); };

            // The settings file is incompatible between languages that LevelEditor and ATF are localized to.
            // For example, the LayoutService saves different Control names depending on the language and so
            //  the Windows layout saved in one language can't be loaded correctly in another language.
            string language = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName; //"en" or "ja"
            if (language == "ja")
            {
                var settingsService = container.GetExportedValue<SettingsService>();
                string nonEnglishPath = settingsService.SettingsPath;
                nonEnglishPath = Path.Combine(Path.GetDirectoryName(nonEnglishPath), "AppSettings_" + language + ".xml");
                settingsService.SettingsPath = nonEnglishPath;
            }

            Application.Run(mainForm); // MAIN LOOP

            container.Dispose();
           
        }
Exemplo n.º 14
0
        static void Main()
        {
            // Important to call these before starting the app.  Otherwise theming and bitmaps may not render correctly.
            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());

            // Using MEF, declare the composable parts that will make up this application
            TypeCatalog catalog = new TypeCatalog(
                typeof(SettingsService),                // persistent settings and user preferences dialog
                typeof(CommandService),                 // handles commands in menus and toolbars
                typeof(ControlHostService),             // docking control host
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardFileExitCommand),        // standard File exit menu command

                typeof(FileDialogService),              // standard Windows file dialogs
                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(AtfUsageLogger),                 // logs computer info to an ATF server
                typeof(WindowLayoutService),            // service to allow multiple window layouts
                typeof(WindowLayoutServiceCommands),    // command layer to allow easy switching between and managing of window layouts
                
                // Client-specific plug-ins
                typeof(Editor),                         // editor class component that creates and saves application documents
                typeof(SchemaLoader),                   // loads schema and extends types

                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );

            // Create the MEF container for the composable parts
            CompositionContainer container = new CompositionContainer(catalog);

            // Create the main form, give it a toolstrip
            ToolStripContainer toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;
            MainForm mainForm = new MainForm(toolStripContainer)
            {
                Text = "Sample Application".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            // Create an MEF composable part from the main form, and add into container
            CompositionBatch batch = new CompositionBatch();
            AttributedModelServices.AddPart(batch, mainForm);
            container.Compose(batch);

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
        }
Exemplo n.º 15
0
        public void ComposeDisposableChildContainer()
        {
            var outerContainer = CreateCompositionContainer();
            Int32Importer outerImporter = new Int32Importer();

            CompositionBatch outerBatch = new CompositionBatch();
            var key = outerBatch.AddExportedValue("Value", 42);
            outerBatch.AddPart(outerImporter);
            outerContainer.Compose(outerBatch);
            Assert.AreEqual(42, outerImporter.Value, "Expected value imported from export");

            Int32Importer innerImporter = new Int32Importer();
            var innerContainer = new CompositionContainer(outerContainer);
            CompositionBatch innerBatch = new CompositionBatch();
            innerBatch.AddPart(innerImporter);

            innerContainer.Compose(innerBatch);
            Assert.AreEqual(42, innerImporter.Value, "Expected value imported from export");
            Assert.AreEqual(42, outerImporter.Value, "Expected value imported from export");

            outerBatch = new CompositionBatch();
            outerBatch.RemovePart(key);
            key = outerBatch.AddExportedValue("Value", -5);
            outerContainer.Compose(outerBatch);
            Assert.AreEqual(-5, innerImporter.Value, "Expected update value imported from export");
            Assert.AreEqual(-5, outerImporter.Value, "Expected updated value imported from export");

            innerContainer.Dispose();
            outerBatch = new CompositionBatch();
            outerBatch.RemovePart(key);
            key = outerBatch.AddExportedValue("Value", 500);
            outerContainer.Compose(outerBatch);
            Assert.AreEqual(500, outerImporter.Value, "Expected updated value imported from export");
            Assert.AreEqual(-5, innerImporter.Value, "Expected value not updated");
        }
        public void Disposing_catalog_should_dispose_parts_implementing_dispose_pattern()
        {
            var innerCatalog = new TypeCatalog(typeof(DisposablePart));
            var cfg = new InterceptionConfiguration();
            var catalog = new InterceptingCatalog(innerCatalog, cfg);
            container = new CompositionContainer(catalog);

            var part = container.GetExportedValueOrDefault<DisposablePart>();
            Assert.That(part.IsDisposed, Is.False);
            container.Dispose();
            Assert.That(part.IsDisposed, Is.True);
        }
Exemplo n.º 17
0
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part = AttributedModelServices.CreatePart(disposable);
            var batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports<AnyPartDisposable>();
            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }
Exemplo n.º 18
0
        public void SharedPart_DisposableRecomposabeImport_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(SharedPartDisposableRecomposable));
            var container = new CompositionContainer(catalog);

            // Setup dependency
            CompositionBatch batch = new CompositionBatch();
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);
            batch = null;

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<SharedPartDisposableRecomposable>());

            refTracker.CollectAndAssert();

            // Lets make sure recomposition doesn't blow anything up here.
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            container.Compose(batch);
            batch = null;

            var exportedValue = (SharedPartDisposableRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target;
            Assert.AreEqual(42, exportedValue.Value);

            container.Dispose();

            Assert.IsTrue(exportedValue.IsDisposed, "Any parts should be disposed with the container!");
        }
Exemplo n.º 19
0
        public void NonSharedPart_Disposable_ShouldBeDisposedWithContainer()
        {
            var catalog = new TypeCatalog(typeof(NonSharedPartDisposable));
            var container = new CompositionContainer(catalog);

            var export = container.GetExportedValue<NonSharedPartDisposable>();

            Assert.IsFalse(export.IsDisposed);

            container.Dispose();

            Assert.IsTrue(export.IsDisposed, "NonSharedParts should be disposed with the container!");
        }
Exemplo n.º 20
0
        static void Main()
        {
            // This startup sequence is based on the "Circuit editor" sample in the Sony ATF repo
            // We want to take advantage of the ATF implementations whereever they exist, but we'll
            // remove the parts that are specific to that circuit editor sample app.

            // It's important to call these before starting the app; otherwise theming and bitmaps
            //  may not render correctly.
            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());
            
            // early engine initialization
            var engineDevice = new GUILayer.EngineDevice();
            GC.KeepAlive(engineDevice);

            var attach0 = new ShaderPatcherLayer.LibraryAttachMarker(engineDevice);
            GC.KeepAlive(attach0);

            XLEBridgeUtils.Utils.AttachLibrary(engineDevice);
            var logRedirect = new XLEBridgeUtils.LoggingRedirect();

            // Enable metadata driven property editing for the DOM
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Create a type catalog with the types of components we want in the application
            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(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(FileDialogService),              // standard Windows file dialogs

                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app
                typeof(HelpAboutCommand),               // Help -> About command

                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardFileExitCommand),        // standard File exit menu command
                // typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                // typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                typeof(StandardLayoutCommands),         // standard Format menu layout commands
                typeof(StandardViewCommands),           // standard View menu commands

                // typeof(PaletteService),                 // global palette, for drag/drop instancing

                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor, like Reset,
                                                        // Reset All, Copy Value, Paste Value, Copy All, Paste All

                typeof(HistoryLister),                  // visual list of undo/redo stack
                typeof(PrototypeLister),                // editable palette of instantiable item groups
                typeof(LayerLister),                    // editable tree view of layers

                typeof(Outputs),                        // passes messages to all log writers
                // typeof(ErrorDialogService),             // displays errors to the user in a message box
                typeof(OutputService),                  // rich text box for displaying error and warning messages. Implements IOutputWriter.
                typeof(DomRecorder),                    // records and displays changes to the DOM for diagnostic purposes

                typeof(Editor),                         // editor which manages circuit documents and controls
                // typeof(SchemaLoader),                   // loads circuit schema and extends types
                // typeof(GroupingCommands),               // circuit group/ungroup commands
                typeof(DiagramControlRegistry),         // circuit controls management
                // typeof(LayeringCommands),               // "Add Layer" command
                // typeof(GraphViewCommands),              // zooming with presets
                typeof(PerformanceMonitor),             // displays the frame rate and memory usage
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                // typeof(ModulePlugin),                   // component that defines circuit module types
                // typeof(TemplateLister),                 // template library for subgraph referencing or instancing 
                // typeof(TemplatingCommands),             // commands for promoting/demoting graph elements to/from template library 
                //typeof(TemplatingSupervisor),         // templated instances copy-on-edit support(optionally)

                typeof(AnnotatingCommands),             // annotating commands
                // typeof(CircuitTestCommands),            // circuit tester commands

                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService),              // provides facilities to run an automated script using the .NET remoting service

                typeof(SkinService),

                typeof(ShaderPatcherLayer.Manager),
                typeof(ShaderFragmentArchive.Archive),
               
                typeof(Controls.DiagramControl),
                typeof(Controls.ShaderFragmentArchiveControl),
                typeof(Controls.DiagramLister),

                typeof(NodeEditorCore.ShaderFragmentArchiveModel),
                typeof(NodeEditorCore.ModelConversion),
                typeof(NodeEditorCore.ShaderFragmentNodeCreator),
                typeof(NodeEditorCore.DiagramDocument),

                typeof(ControlsLibraryExt.Commands.CommonCommands),
                typeof(ControlsLibraryExt.Material.MaterialInspector),
                typeof(ControlsLibraryExt.Material.MaterialSchemaLoader),
                typeof(ControlsLibraryExt.ModelView.ActiveModelView),

                typeof(ActiveMaterialContext),
                typeof(DiagramCommands)
            );

            // enable use of the system clipboard
            StandardEditCommands.UseSystemClipboard = true;

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // This is bit wierd, but we're going to add the container to itself.
            // This will create a tight circular dependency, of course
            // It's also not ideal by the core DI pattern. 
            // But it's useful for us, because we want to use the same container to construct
            // objects (and also to retrieve global instances).
            container.ComposeExportedValue<ExportProvider>(container);
            container.ComposeExportedValue<CompositionContainer>(container);

            // Configure the main Form
            var batch = new CompositionBatch();
            var mainForm = new MainForm(new ToolStripContainer())
                {
                    Text = Application.ProductName //,
                    // Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
                };
            // Sce.Atf.Direct2D.D2dFactory.EnableResourceSharing(mainForm.Handle);

            // Add the main Form instance, etc., to the container
            batch.AddPart(mainForm);
            // batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Circuit-Editor-Sample".Localize()));
            container.Compose(batch);

            // We need to attach compilers for models, etc
            engineDevice.AttachDefaultCompilers();

            container.InitializeAll();
            Application.Run(mainForm);
            container.Dispose();
            mainForm.Dispose();

            logRedirect.Dispose();
            engineDevice.PrepareForShutdown();
            XLEBridgeUtils.Utils.DetachLibrary();
            attach0.Dispose();
            engineDevice.Dispose();
        }
Exemplo n.º 21
0
        public void ParentChildContainerTest()
        {
            var catalog = new AssemblyCatalog(typeof(FilteringCatalogTests).Assembly);
            var parent = new CompositionContainer(catalog);

            var filteredCat = new FilteringCatalog(catalog, new HasCreationPolicy(CreationPolicy.NonShared));
            var child = new CompositionContainer(filteredCat, parent);

            var root = child.GetExportedValue<Root>();
            var dep1 = root.Dep;
            var dep2 = dep1.Dep;
            var dep3 = dep2.Dep;

            Assert.That(root.Disposed, Is.False);
            Assert.That(dep1.Disposed, Is.False);
            Assert.That(dep2.Disposed, Is.False);
            Assert.That(dep3.Disposed, Is.False);

            child.Dispose();

            Assert.That(root.Disposed, Is.True); // Disposed as it was created by the child container
            Assert.That(dep1.Disposed, Is.True); // Disposed as it was created by the child container
            Assert.That(dep2.Disposed, Is.False);
            Assert.That(dep3.Disposed, Is.False);
        }
Exemplo n.º 22
0
        static void Main()
        {
            // important to call these before creating application host
            Application.EnableVisualStyles();
            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(FileDialogService),          // proivdes standard Windows file dialogs, to let the user open and close files. Used by SkinService.
                typeof(SkinService),                // allows for customization of an application’s appearance by using inheritable properties that can be applied at run-time
                typeof(StatusService),              // status bar at bottom of main Form
                typeof(CommandService),             // handles commands in menus and toolbars
                typeof(ControlHostService),         // docking control host

                typeof(StandardFileExitCommand),    // standard File exit menu command
                typeof(HelpAboutCommand),           // Help -> About command
                typeof(AtfUsageLogger),             // logs computer info to an ATF server
                typeof(CrashLogger),                // logs unhandled exceptions to an ATF server

                typeof(ContextRegistry),            // component that tracks application contexts; needed for context menu 

                // add target info plugins and TargetEnumerationService
                typeof(Deci4pTargetProvider),       // provides information about development devices available via Deci4p
                typeof(TcpIpTargetProvider),        // provides information about development devices available via TCP/IP
                typeof(TargetCommands),             // commands to operate on currently selected targets. 
                typeof(TargetEnumerationService)    // queries and enumerates target objects, consuming target providers created by the application
             );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form
            var batch = new CompositionBatch();
            var mainForm = new MainForm(new ToolStripContainer())
            {
                Text = "ATF TargetManager Sample".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            // Add the main Form instance to the container
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Target-Manager-Sample".Localize()));
            container.Compose(batch);

            var controlHostService = container.GetExportedValue<ControlHostService>();
            controlHostService.RegisteredCommands = ControlHostService.CommandRegister.None; // turn off standard window commands for simpele & single window UI 

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
           
        }
Exemplo n.º 23
0
        public static void Main(string[] args)
        {
            // It's important to call these before starting the app; otherwise theming and bitmaps
            //  may not render correctly.
            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());

            // Enable metadata driven property editing for the DOM
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Create a type catalog with the types of components we want in the application
            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(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(FileDialogService),              // standard Windows file dialogs

                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app
                typeof(SkinService),                    // skin service.
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardFileExitCommand),        // standard File exit menu command
                typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                typeof(StandardLayoutCommands),         // standard Format menu layout commands
                typeof(StandardViewCommands),           // standard View menu commands
                
                //StandardPrintCommands does not currently work with Direct2D
                //typeof(StandardPrintCommands),        // standard File menu print commands

                typeof(HelpAboutCommand),               // Help -> About command

                typeof(PaletteService),                 // global palette, for drag/drop instancing
                typeof(HistoryLister),                  // visual list of undo/redo stack
                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor, like Reset,
                                                        //  Reset All, Copy Value, Paste Value, Copy All, Paste All

                typeof(PrototypeLister),                // editable palette of instantiable item groups

                typeof(Outputs),                        // passes messages to all log writers
                typeof(ErrorDialogService),             // displays errors to the user in a message box

                typeof(Editor),                         // editor which manages FSM documents and controls
                typeof(PaletteClient),                  // component which adds items to palette
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                typeof(SchemaLoader),                   // loads schema and extends types

                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form
            var batch = new CompositionBatch();
            var mainForm = new MainForm(new ToolStripContainer())
            {
                Text = Application.ProductName,
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };
            Sce.Atf.Direct2D.D2dFactory.EnableResourceSharing(mainForm.Handle);

            // Add the main Form instance to the container
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-FSM-Editor-Sample".Localize()));
            container.Compose(batch);

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            // important to call these before creating application host
            Application.EnableVisualStyles();
            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(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(FileDialogService),              // standard Windows file dialogs

                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app

                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardFileExitCommand),        // standard File exit menu command
                typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                //typeof(StandardLockCommands),           // standard Edit menu lock/unlock commands
                typeof(HelpAboutCommand),               // Help -> About command

                typeof(PaletteService),                 // global palette, for drag/drop instancing

                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor

                typeof(Outputs),                        // passes messages to all log writers
                typeof(ErrorDialogService),             // displays errors to the user a in message box

                typeof(HelpAboutCommand),               // custom command component to display Help/About dialog
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                typeof(Editor),                         // editor which manages event sequence documents
                typeof(DomTypes),                       // defines the DOM's metadata for this sample app
                typeof(PaletteClient),                  // component which adds items to palette
                typeof(EventListEditor),                // adds drag/drop and context menu to event sequence ListViews
                typeof(ResourceListEditor),             // adds "slave" resources ListView control, drag/drop and context menu
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form and add it to the composition container
            var batch = new CompositionBatch();
            var toolStripContainer = new ToolStripContainer();
            var mainForm = new MainForm(toolStripContainer)
            {
                Text = "Simple DOM, No XML, Editor Sample".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Simple-DOM-No-XML-Editor-Sample".Localize()));

            // Compose the MEF container
            container.Compose(batch);

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
        }
Exemplo n.º 25
0
        static void Main()
        {
            // 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
#if true
            // 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(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                typeof(HelpAboutCommand),               // Help -> About command

                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(PropertyEditor),                 // property grid for editing selected objects
                //typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor, like Reset,
                                                        //  Reset All, Copy Value, Paste Value, Copy All, Paste All

                typeof(Editor),                         // code editor component
                typeof(SchemaLoader),                   // loads schema and extends types
                typeof(CharacterEditor),
                typeof(CharacterSettingsCommands)

             );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            var toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;

            var mainForm = new MainForm(toolStripContainer);
            mainForm.Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage));

            mainForm.Text = "Butterfly Engine".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>();
            tabCommands.IsDocumentControl = controlInfo => controlInfo.Client is Editor;

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
#else
            var mainForm = new FormTest
            {
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            Application.Run(mainForm);
#endif

        }
Exemplo n.º 26
0
        static void Main()
        {
            // It's important to call these before starting the app; otherwise theming and bitmaps
            // may not render correctly.
            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());

            // Register the embedded image resources so that they will be available for all users of ResourceUtil,
            //  such as the PaletteService.
            ResourceUtil.Register(typeof(Resources));

            // Enable metadata driven property editing for the DOM
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Create a type catalog with the types of components we want in the application
            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(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(DocumentRegistry),               // central document registry with change notification
                typeof(FileDialogService),              // standard Windows file dialogs
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                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(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(HelpAboutCommand),               // Help -> About command

                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands

                typeof(PaletteService),                 // global palette, for drag/drop instancing
                typeof(HistoryLister),                  // visual list of undo/redo stack
                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor, like Reset,
                                                        //  Reset All, Copy Value, Paste Value, Copy All, Paste All
                typeof(CurveEditor),                    // edits curves using the CurveEditingControl

                typeof(SchemaLoader),                   // component that loads XML schema and sets up types
                typeof(Editor),                         // component that manages UI documents
                typeof(PaletteClient),                  // component that adds UI types to palette
                typeof(TreeLister),                     // component that displays the UI in a tree control
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                typeof(DomExplorer),                    // component that gives diagnostic view of DOM
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form with a ToolStripContainer so the CommandService can
            //  generate toolbars.
            var toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;
            var mainForm = new MainForm(toolStripContainer)
            {
                Text = "Dom Tree Editor".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            // Add the main Form instance to the container
            var batch = new CompositionBatch();
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-DOM-Tree-Editor-Sample".Localize()));
            container.Compose(batch);

            // 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();

            // Example of programmatic layout creation:
            {
                var windowLayoutService = container.GetExportedValue<IWindowLayoutService>();
                var dockStateProvider = container.GetExportedValue<IDockStateProvider>();

                // Load custom XML and add it to the Window Layout Service
                int layoutNum = 0;
                Assembly assembly = Assembly.GetExecutingAssembly();
                foreach (string resourceName in assembly.GetManifestResourceNames())
                {
                    if (resourceName.Contains("Layout") && resourceName.EndsWith(".xml"))
                    {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(assembly.GetManifestResourceStream(resourceName));

                        layoutNum++;
                        windowLayoutService.SetOrAddLayout(dockStateProvider, "Programmatic Layout " + layoutNum, xmlDoc.InnerXml);
                    }
                }
            }

            // 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);

            // Give components a chance to clean up.
            container.Dispose();
        }
Exemplo n.º 27
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(HelpAboutCommand),               // Help -> About command
                typeof(AtfUsageLogger),                 // logs computer info to an ATF server
                typeof(CrashLogger),                    // logs unhandled exceptions to an ATF server
                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(Editor),                         // code editor component
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService),              // provides facilities to run an automated script using the .NET remoting service
                typeof(PerforceService),                // Perforce plugin
                typeof(SourceControlCommands),          // source control commmands to interact with Perforce plugin
                typeof(SourceControlContext)            // source control context component
                );

            var container = new CompositionContainer(catalog);

            var toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;

            var mainForm = new MainForm(toolStripContainer);
            var image = GdiUtil.GetImage("CodeEditor.Resources.File_edit.ico");
            mainForm.Icon = GdiUtil.CreateIcon(image, 32, true);

            mainForm.Text = "Code Editor".Localize();

            var batch = new CompositionBatch();
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Code-Editor-Sample".Localize()));
            container.Compose(batch);

            // 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();
        }
Exemplo n.º 28
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
                        
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CurrentCulture;
            Localizer.SetStringLocalizer(new EmbeddedResourceStringLocalizer());

            // Enable metadata driven property editing for the DOM
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Create a type catalog with the types of components we want in the application
            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(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(FileDialogService),              // standard Windows file dialogs
                typeof(DocumentRegistry),               // central document registry with change notification                
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title                                
                typeof(StandardFileExitCommand),        // standard File exit menu command                                                               
                typeof(HelpAboutCommand),               // Help -> About command
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService),              // provides facilities to run an automated script using the .NET remoting service
                typeof(Outputs),                        // passes messages to all IOutputWriter components
                typeof(ShoutOutputService),             // rich text box for displaying error and warning messages. Implements IOutputWriter

                typeof(Sce.Atf.Atgi.AtgiResolver),      // loads ATGI resources from a file
                typeof(Sce.Atf.Collada.ColladaResolver),// loads Collada resources from a file

                // this sample
                typeof(ModelViewer),                    // recognizes model file extensions and uses the above model resolvers to load models
                typeof(RenderCommands),                 // provides commands for switching the RenderView's rendering mode, etc.
                typeof(RenderView)                      // displays a 3D scene in a Windows Control
                );


            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form
            var batch = new CompositionBatch();
            var mainForm = new MainForm(new ToolStripContainer())
            {
                Text = "Model Viewer".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };
            // Add the main Form instance to the container
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Model-Viewer-Sample".Localize()));
            container.Compose(batch);

            var stdfile = container.GetExportedValue<StandardFileCommands>();
            stdfile.RegisterCommands = StandardFileCommands.CommandRegister.FileOpen;

            // Initialize components             
            foreach (IInitializable initializable in container.GetExportedValues<IInitializable>())
                initializable.Initialize();      
          
            // 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);

            // Give components a chance to clean up.
            container.Dispose();
        }
Exemplo n.º 29
0
        public void ThreadSafeCompositionContainer()
        {
            TypeCatalog catalog = new TypeCatalog(typeof(SimpleExporter));

            CompositionContainer container = new CompositionContainer(catalog, true);
            Int32Importer importer = new Int32Importer();

            CompositionBatch batch = new CompositionBatch();
            batch.AddParts(importer, new Int32Exporter(42));
            container.Compose(batch);

            Assert.IsNotNull(container.GetExportedValue<SimpleExporter>());
            Assert.AreEqual(42, importer.Value, "Expected value imported from export");

            container.Dispose();

        }
Exemplo n.º 30
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 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());

            // Enable metadata driven property editing for the DOM
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            // Create a type catalog with the types of components we want in the application
            var catalog = new TypeCatalog(

                typeof(CommandService),                 // handles commands in menus and toolbars
                typeof(ControlHostService),             // docking control host
                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(FileDialogService),
                typeof(SkinService),
                typeof(StandardFileExitCommand),        // standard File exit menu command
                typeof(StandardEditHistoryCommands),    // tracks document changes and updates main form title
                typeof(HelpAboutCommand),               // Help -> About command
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor
                typeof(SettingsService),
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService),              // provides facilities to run an automated script using the .NET remoting service

                typeof(SchemaLoader),                   // component that loads XML schema and sets up types
                typeof(Editor)                          // component that manages UI documents
                );

            // Set up the MEF container with these components
            var container = new CompositionContainer(catalog);

            // Configure the main Form

            // Configure the main Form with a ToolStripContainer so the CommandService can
            //  generate toolbars.
            var toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;
            var mainForm = new MainForm(toolStripContainer)
            {
                Text = "DOM Property Editor".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            // Add the main Form instance to the container
            var batch = new CompositionBatch();
            batch.AddPart(mainForm);
            // batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-DOM-Tree-Editor-Sample".Localize()));
            container.Compose(batch);

            // 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();

            var propEditor = container.GetExportedValue<PropertyEditor>();
            propEditor.PropertyGrid.PropertySorting = Sce.Atf.Controls.PropertyEditing.PropertySorting.Categorized;
            // 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);

            // Give components a chance to clean up.
            container.Dispose();

        }
Exemplo n.º 31
0
        public void Execute()
        {
            //
            // カタログ構築.
            //  AggregateCatalogは、複数のCatalogを一つにまとめる役割を持つ。
            //
            var catalog = new AggregateCatalog();
            // AssemblyCatalogを利用して、自分自身のアセンブリをカタログに追加.
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(MEFSamples01).Assembly));

            //
            // コンテナを構築.
            //
            _container = new CompositionContainer(catalog);
            try
            {
                // 合成実行.
                _container.ComposeParts(this);

                // 実行.
                foreach (var lazyObj in _exporters)
                {
                    //
                    // メタデータを調べ、合致したもののみを実行する.
                    // Lazy<T, TMetadata>.Valueを呼ばない限りインスタンスは作成されない。
                    //
                    if (lazyObj.Metadata.Symbol == "SECOND")
                    {
                        Output.WriteLine(lazyObj.Value.Name);
                    }
                }
            }
            catch (CompositionException ex)
            {
                // 合成に失敗した場合.
                Output.WriteLine(ex.ToString());
            }

            if (_container != null)
            {
                _container.Dispose();
            }
        }
Exemplo n.º 32
0
        //=====================================================================

        /// <summary>
        /// Call this method to perform the build on the project.
        /// </summary>
        public void Build()
        {
            Project msBuildProject = null;
            ProjectItem projectItem;
            string resolvedPath, helpFile, languageFile, scriptFile, hintPath, message = null;
            SandcastleProject originalProject = null;

            System.Diagnostics.Debug.WriteLine("Build process starting\r\n");

            try
            {
                taskRunner = new TaskRunner(this);

                // If the project isn't using final values suitable for the build, create a copy of the
                // project that is using final values.
                if(!project.UsingFinalValues)
                {
                    originalProject = project;
                    project = new SandcastleProject(originalProject.MSBuildProject);
                }

                Assembly asm = Assembly.GetExecutingAssembly();

                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
                this.ReportProgress(BuildStep.Initializing, "[{0}, version {1}]", fvi.ProductName, fvi.ProductVersion);

                buildStart = stepStart = DateTime.Now;

                // The version of MSBuild to use is based on the tools version set in the project
                msBuildExePath = Path.Combine(ProjectCollection.GlobalProjectCollection.Toolsets.First(
                    t => t.ToolsVersion == project.MSBuildProject.ToolsVersion).ToolsPath, "MSBuild.exe");

                // Get the location of the template files
                templateFolder = ComponentUtilities.ToolsFolder + @"Templates\";

                // Make sure we start out in the project's output folder in case the output folder is relative
                // to it.
                projectFolder = Path.GetDirectoryName(originalProjectName);

                if(projectFolder.Length == 0)
                    projectFolder = Directory.GetCurrentDirectory();

                projectFolder += @"\";

                Directory.SetCurrentDirectory(projectFolder);

                this.ReportProgress("Creating output and working folders...");

                outputFolder = project.OutputPath;

                if(String.IsNullOrEmpty(outputFolder))
                    outputFolder = Directory.GetCurrentDirectory();
                else
                    outputFolder = Path.GetFullPath(outputFolder);

                if(!Directory.Exists(outputFolder))
                    Directory.CreateDirectory(outputFolder);

                if(outputFolder[outputFolder.Length - 1] != '\\')
                    outputFolder += @"\";

                // Create the log file.  The log may be in a folder other than the output so make sure it exists
                // too.
                if(!Directory.Exists(Path.GetDirectoryName(this.LogFilename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(this.LogFilename));

                swLog = new StreamWriter(this.LogFilename);

                swLog.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<shfbBuild product=\"{0}\" " +
                    "version=\"{1}\" projectFile=\"{2}\" started=\"{3}\">\r\n<buildStep step=\"{4}\">",
                    fvi.ProductName, fvi.ProductVersion, originalProjectName, DateTime.Now,
                    BuildStep.Initializing);

                if(project.WorkingPath.Path.Length == 0)
                    workingFolder = outputFolder + @"Working\";
                else
                    workingFolder = project.WorkingPath;

                if((project.HelpFileFormat & HelpFileFormats.Website) != 0)
                    BuildProcess.VerifySafePath("OutputPath", outputFolder, projectFolder);

                // The output folder and the working folder cannot be the same
                if(workingFolder == outputFolder)
                    throw new BuilderException("BE0030", "The OutputPath and WorkingPath properties cannot be " +
                        "set to the same path");

                // Make sure we can find the tools
                this.FindTools();

                // Check for the SHFBROOT environment variable.  It may not be present yet if a reboot hasn't
                // occurred after installation.  In such cases, set it to the proper folder for this process so
                // that projects can be loaded and built.
                if(Environment.GetEnvironmentVariable("SHFBROOT") == null)
                {
                    // We won't issue a warning since it may not be defined in some build environments such as
                    // on a build server.  In such cases, it is passed in as a command line option to MSBuild.
                    // Storing it in the environment here lets the SHFB build projects work as expected.
                    this.ReportProgress("The SHFBROOT system environment variable was not found.  This " +
                        "variable is usually created during installation and may require a reboot.  It has " +
                        "been defined temporarily for this process as: SHFBROOT={0}",
                        ComponentUtilities.ToolsFolder);

                    Environment.SetEnvironmentVariable("SHFBROOT", ComponentUtilities.ToolsFolder);
                }

                this.ReportProgress("Locating components in the following folder(s):");

                if(!String.IsNullOrEmpty(project.ComponentPath))
                    this.ReportProgress("    {0}", project.ComponentPath);

                this.ReportProgress("    {0}", Path.GetDirectoryName(project.Filename));

                this.ReportProgress("    {0}", ComponentUtilities.ComponentsFolder);
                this.ReportProgress("    {0}", ComponentUtilities.ToolsFolder);

                // Get the framework reflection data settings to use for the build
                reflectionDataDictionary = new ReflectionDataSetDictionary(new[] { project.ComponentPath,
                    Path.GetDirectoryName(project.Filename) });
                frameworkReflectionData = reflectionDataDictionary.CoreFrameworkByTitle(project.FrameworkVersion, true);

                if(frameworkReflectionData == null)
                    throw new BuilderException("BE0071", String.Format(CultureInfo.CurrentCulture,
                        "Unable to locate information for the project framework version '{0}' or a suitable " +
                        "redirected version on this system.  See error number help topic for details.",
                        project.FrameworkVersion));

                this.ReportProgress("Framework reflection data location: {0}", this.FrameworkReflectionDataFolder);

                if(!Directory.EnumerateFiles(this.FrameworkReflectionDataFolder, "*.xml").Any())
                    throw new BuilderException("BE0032", "Reflection data files for the selected framework " +
                        "do not exist yet (" + frameworkReflectionData.Title + ").  See help file for " +
                        "details about this error number.");

                // Warn if a different framework is being used for the build
                if(frameworkReflectionData.Title != project.FrameworkVersion)
                    this.ReportWarning("BE0072", "Project framework version '{0}' not found.  It has been " +
                        "redirected and will use '{1}' instead.", project.FrameworkVersion,
                        frameworkReflectionData.Title);

                // Get the composition container used to find build components in the rest of the build process
                componentContainer = ComponentUtilities.CreateComponentContainer(new[] { project.ComponentPath,
                    Path.GetDirectoryName(project.Filename) }, this.CancellationToken);

                syntaxGenerators = componentContainer.GetExports<ISyntaxGeneratorFactory,
                    ISyntaxGeneratorMetadata>().Select(sf => sf.Metadata).ToList();
                buildComponents = componentContainer.GetExports<BuildComponentFactory,
                    IBuildComponentMetadata>().GroupBy(c => c.Metadata.Id).Select(g => g.First()).ToDictionary(
                        key => key.Metadata.Id, value => value.Value);

                // Figure out which presentation style to use
                var style = componentContainer.GetExports<PresentationStyleSettings,
                    IPresentationStyleMetadata>().FirstOrDefault(s => s.Metadata.Id.Equals(
                        project.PresentationStyle, StringComparison.OrdinalIgnoreCase));

                if(style == null)
                    throw new BuilderException("BE0001", "The PresentationStyle property value of '" +
                        project.PresentationStyle + "' is not recognized as a valid presentation style definition");

                presentationStyle = style.Value;

                this.ReportProgress("Using presentation style '{0}' located in '{1}'", style.Metadata.Id,
                    Path.Combine(presentationStyle.Location, presentationStyle.BasePath ?? String.Empty));

                var psErrors = presentationStyle.CheckForErrors();

                if(psErrors.Any())
                    throw new BuilderException("BE0004", String.Format(CultureInfo.CurrentCulture,
                        "The selected presentation style ({0}) is not valid.  Reason(s):\r\n{1}",
                        style.Metadata.Id, String.Join("\r\n", psErrors)));

                // If the presentation style does not support one or more of the selected help file formats,
                // stop now.
                if((project.HelpFileFormat & ~presentationStyle.SupportedFormats) != 0)
                    throw new BuilderException("BE0074", String.Format(CultureInfo.CurrentCulture,
                        "The selected presentation style ({0}) does not support one or more of the selected " +
                        "help file formats.  Supported formats: {1}", style.Metadata.Id,
                        presentationStyle.SupportedFormats));

                // Create the substitution tag replacement handler now as we have everything it needs
                substitutionTags = new SubstitutionTagReplacement(this);

                // Load the plug-ins if necessary
                if(project.PlugInConfigurations.Count != 0 || presentationStyle.PlugInDependencies.Count != 0)
                    this.LoadPlugIns();

                this.ExecutePlugIns(ExecutionBehaviors.After);

                try
                {
                    if(Directory.Exists(workingFolder))
                    {
                        // Clear any data from a prior run
                        this.ReportProgress(BuildStep.ClearWorkFolder, "Clearing working folder...");
                        BuildProcess.VerifySafePath("WorkingPath", workingFolder, projectFolder);

                        if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                        {
                            this.ExecutePlugIns(ExecutionBehaviors.Before);

                            try
                            {
                                Directory.Delete(workingFolder, true);
                            }
                            catch(IOException ioEx)
                            {
                                this.ReportProgress("    Not all prior output was removed from '{0}': {1}",
                                    workingFolder, ioEx.Message);
                            }
                            catch(UnauthorizedAccessException uaEx)
                            {
                                this.ReportProgress("    Not all prior output was removed from '{0}': {1}",
                                    workingFolder, uaEx.Message);
                            }

                            this.ExecutePlugIns(ExecutionBehaviors.After);
                        }
                    }

                    // For MS Help Viewer, the HTML Help Name cannot contain periods, ampersands, or pound signs
                    if((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0 &&
                      this.ResolvedHtmlHelpName.IndexOfAny(new[] { '.', '#', '&' }) != -1)
                        throw new BuilderException("BE0075", "For MS Help Viewer builds, the HtmlHelpName property " +
                            "cannot contain periods, ampersands, or pound signs as they are not valid in the " +
                            "help file name.");

                    // If the help file is open, it will fail to build so try to get rid of it now before we
                    // get too far into it.
                    helpFile = outputFolder + this.ResolvedHtmlHelpName + ".chm";

                    if((project.HelpFileFormat & HelpFileFormats.HtmlHelp1) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);

                    helpFile = Path.ChangeExtension(helpFile, ".mshc");

                    if((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);

                    if((project.HelpFileFormat & HelpFileFormats.Website) != 0)
                    {
                        helpFile = outputFolder + "Index.aspx";

                        if(File.Exists(helpFile))
                            File.Delete(helpFile);

                        helpFile = Path.ChangeExtension(helpFile, ".html");

                        if(File.Exists(helpFile))
                            File.Delete(helpFile);
                    }

                    helpFile = outputFolder + this.ResolvedHtmlHelpName + ".docx";

                    if((project.HelpFileFormat & HelpFileFormats.OpenXml) != 0 && File.Exists(helpFile))
                        File.Delete(helpFile);
                }
                catch(IOException ex)
                {
                    throw new BuilderException("BE0025", "Unable to remove prior build output: " + ex.Message);
                }
                catch
                {
                    throw;
                }

                if((project.HelpFileFormat & (HelpFileFormats.Website | HelpFileFormats.Markdown)) != 0)
                {
                    this.ReportProgress("-------------------------------");
                    this.ReportProgress("Clearing any prior web/markdown output...");

                    // Purge all files and folders from the output path except for the working folder and the
                    // build log.  Read-only and/or hidden files and folders are ignored as they are assumed to
                    // be under source control.
                    foreach(string file in Directory.EnumerateFiles(outputFolder))
                        if(!file.EndsWith(Path.GetFileName(this.LogFilename), StringComparison.Ordinal))
                            if((File.GetAttributes(file) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                                File.Delete(file);
                            else
                                this.ReportProgress("    Ignoring read-only/hidden file {0}", file);

                    foreach(string folder in Directory.EnumerateDirectories(outputFolder))
                        try
                        {
                            // Ignore the working folder in case it wasn't removed above
                            if(!folder.Equals(workingFolder.Substring(0, workingFolder.Length - 1), StringComparison.OrdinalIgnoreCase))
                            {
                                // Some source control providers have a mix of read-only/hidden files within a
                                // folder that isn't read-only/hidden (i.e. Subversion).  In such cases, leave
                                // the folder alone.
                                if(Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Any(
                                  f => (File.GetAttributes(f) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) != 0))
                                {
                                    this.ReportProgress("    Did not delete folder '{0}' as it contains " +
                                        "read-only or hidden folders/files", folder);
                                }
                                else
                                    if((File.GetAttributes(folder) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                                        Directory.Delete(folder, true);
                                    else
                                        this.ReportProgress("    Ignoring read-only/hidden folder {0}", folder);
                            }
                        }
                        catch(IOException ioEx)
                        {
                            this.ReportProgress("    Ignoring folder '{0}': {1}", folder, ioEx.Message);
                        }
                        catch(UnauthorizedAccessException uaEx)
                        {
                            this.ReportProgress("    Ignoring folder '{0}': {1}", folder, uaEx.Message);
                        }
                }

                Directory.CreateDirectory(workingFolder);

                // Validate the documentation source information, gather assembly and reference info, and copy
                // XML comments files to the working folder.
                this.ValidateDocumentationSources();

                // Transform the shared builder content files
                language = project.Language;
                languageFile = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ToolResourceItemsPath),
                    language.Name + ".xml");

                this.ReportProgress(BuildStep.GenerateSharedContent, "Generating shared content files ({0}, {1})...",
                    language.Name, language.DisplayName);

                if(!File.Exists(languageFile))
                {
                    languageFile = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ToolResourceItemsPath),
                        "en-US.xml");

                    // Warn the user about the default being used
                    this.ReportWarning("BE0002", "Help file builder content for the '{0}, {1}' language could " +
                        "not be found.  Using 'en-US, English (US)' defaults.", language.Name, language.DisplayName);
                }

                // See if the user has translated the Sandcastle resources.  If not found, default to US English.
                languageFolder = Path.Combine(presentationStyle.ResolvePath(presentationStyle.ResourceItemsPath),
                    language.Name);

                if(Directory.Exists(languageFolder))
                    languageFolder = language.Name + @"\";
                else
                {
                    // Warn the user about the default being used.  The language will still be used for the help
                    // file though.
                    if(language.Name != "en-US")
                        this.ReportWarning("BE0003", "Sandcastle shared content for the '{0}, {1}' language " +
                            "could not be found.  Using 'en-US, English (US)' defaults.", language.Name,
                            language.DisplayName);

                    languageFolder = String.Empty;
                }

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    substitutionTags.TransformTemplate(Path.GetFileName(languageFile), Path.GetDirectoryName(languageFile),
                        workingFolder);
                    File.Move(workingFolder + Path.GetFileName(languageFile), workingFolder + "SHFBContent.xml");

                    // Copy the stop word list
                    languageFile = Path.Combine(ComponentUtilities.ToolsFolder, @"PresentationStyles\Shared\" +
                        @"StopWordList\" + Path.GetFileNameWithoutExtension(languageFile) +".txt");
                    File.Copy(languageFile, workingFolder + "StopWordList.txt");
                    File.SetAttributes(workingFolder + "StopWordList.txt", FileAttributes.Normal);

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Generate the API filter used by MRefBuilder
                this.GenerateApiFilter();

                // Generate the reflection information
                this.ReportProgress(BuildStep.GenerateReflectionInfo, "Generating reflection information...");

                reflectionFile = workingFolder + "reflection.org";

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    substitutionTags.TransformTemplate("MRefBuilder.config", templateFolder, workingFolder);
                    scriptFile = substitutionTags.TransformTemplate("GenerateRefInfo.proj", templateFolder, workingFolder);

                    try
                    {
                        msBuildProject = new Project(scriptFile);

                        // Add the references
                        foreach(var r in referenceDictionary.Values)
                        {
                            projectItem = msBuildProject.AddItem(r.Item1, r.Item2, r.Item3)[0];

                            // Make sure hint paths are correct by adding the project folder to any relative
                            // paths.  Skip any containing MSBuild variable references.
                            if(projectItem.HasMetadata(BuildItemMetadata.HintPath))
                            {
                                hintPath = projectItem.GetMetadataValue(BuildItemMetadata.HintPath);

                                if(!Path.IsPathRooted(hintPath) && hintPath.IndexOf("$(",
                                  StringComparison.Ordinal) == -1)
                                {
                                    hintPath = FilePath.GetFullPath(Path.Combine(projectFolder, hintPath));

                                    // If the full path length would exceed the system maximums, make it relative
                                    // to keep it under the maximum lengths.
                                    if(hintPath.Length > 259 || Path.GetDirectoryName(hintPath).Length > 247)
                                        hintPath = FolderPath.AbsoluteToRelativePath(workingFolder, hintPath);

                                    projectItem.SetMetadataValue(BuildItemMetadata.HintPath, hintPath);
                                }
                            }
                        }

                        // Add the assemblies to document
                        foreach(string assemblyName in assembliesList)
                            msBuildProject.AddItem("Assembly", assemblyName);

                        msBuildProject.Save(scriptFile);
                    }
                    finally
                    {
                        // If we loaded it, we must unload it.  If not, it is cached and may cause problems later.
                        if(msBuildProject != null)
                        {
                            ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject);
                            ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject.Xml);
                        }
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    // Silverlight build targets are only available for 32-bit builds regardless of the framework
                    // version and require the 32-bit version of MSBuild in order to load the target file correctly.
                    if(project.FrameworkVersion.StartsWith("Silverlight", StringComparison.OrdinalIgnoreCase))
                        taskRunner.Run32BitProject("GenerateRefInfo.proj", false);
                    else
                        taskRunner.RunProject("GenerateRefInfo.proj", false);

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // If this was a partial build used to obtain API information, stop now
                if(this.PartialBuildType == PartialBuildType.GenerateReflectionInfo)
                {
                    commentsFiles.Save();
                    goto AllDone;       // Yeah, I know it's evil but it's quick
                }

                // Transform the reflection output based on the document model and create the topic manifest
                this.ReportProgress(BuildStep.TransformReflectionInfo, "Transforming reflection output...");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    scriptFile = substitutionTags.TransformTemplate("TransformManifest.proj", templateFolder, workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    taskRunner.RunProject("TransformManifest.proj", false);

                    // Change the reflection file extension before running the ExecutionBehaviors.After plug-ins
                    // so that the plug-ins (if any) get the correct filename.
                    reflectionFile = Path.ChangeExtension(reflectionFile, ".xml");

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }
                else
                    reflectionFile = Path.ChangeExtension(reflectionFile, ".xml");

                // If this was a partial build used to obtain information for namespace and namespace group
                // comments, stop now.
                if(this.PartialBuildType == PartialBuildType.TransformReflectionInfo)
                {
                    commentsFiles.Save();
                    goto AllDone;       // Yeah, I know it's evil but it's quick
                }

                // Load the transformed reflection information file
                reflectionFile = workingFolder + "reflection.xml";

                // If there is nothing to document, stop the build
                if(!ComponentUtilities.XmlStreamAxis(reflectionFile, "api").Any())
                    throw new BuilderException("BE0033", "No APIs found to document.  See error topic in " +
                        "help file for details.");

                // Generate namespace summary information
                this.GenerateNamespaceSummaries();

                // Expand <inheritdoc /> tags?
                if(commentsFiles.ContainsInheritedDocumentation)
                {
                    commentsFiles.Save();

                    // Transform the reflection output.
                    this.ReportProgress(BuildStep.GenerateInheritedDocumentation,
                        "Generating inherited documentation...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        substitutionTags.TransformTemplate("GenerateInheritedDocs.config", templateFolder, workingFolder);
                        scriptFile = substitutionTags.TransformTemplate("GenerateInheritedDocs.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("GenerateInheritedDocs.proj", true);
                        
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // This should always be last so that it overrides comments in the project XML comments files
                    commentsFiles.Add(new XmlCommentsFile(workingFolder + "_InheritedDocs_.xml"));
                }

                commentsFiles.Save();

                this.EnsureOutputFoldersExist(null);

                // Copy conceptual content files if there are topics or tokens.  Tokens can be replaced in
                // XML comments files so we check for them too.
                if(this.ConceptualContent.ContentLayoutFiles.Count != 0 || this.ConceptualContent.TokenFiles.Count != 0)
                {
                    this.ReportProgress(BuildStep.CopyConceptualContent, "Copying conceptual content...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ConceptualContent.CopyContentFiles(this);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    this.ReportProgress(BuildStep.CreateConceptualTopicConfigs,
                        "Creating conceptual topic configuration files...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ConceptualContent.CreateConfigurationFiles(this);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }
                else    // Create an empty xmlComp folder required by the build configuration
                    Directory.CreateDirectory(Path.Combine(workingFolder, "xmlComp"));

                // Copy the additional content
                this.CopyAdditionalContent();

                // Merge the conceptual and additional content TOC info
                this.MergeConceptualAndAdditionalContentTocInfo();

                // Generate the intermediate table of contents file.  This
                // must occur prior to running BuildAssembler as the MS Help
                // Viewer build component is dependent on the toc.xml file.
                this.ReportProgress(BuildStep.GenerateIntermediateTableOfContents,
                    "Generating intermediate table of contents file...");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    scriptFile = substitutionTags.TransformTemplate("GenerateIntermediateTOC.proj", templateFolder,
                        workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    taskRunner.RunProject("GenerateIntermediateTOC.proj", false);

                    // Determine the API content placement
                    this.DetermineApiContentPlacement();

                    // If there is conceptual content, generate the conceptual intermediate TOC
                    if(toc != null)
                    {
                        this.ReportProgress("Generating conceptual content intermediate TOC file...");

                        toc.SaveToIntermediateTocFile((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0 ?
                            this.RootContentContainerId : null, project.TocOrder, workingFolder + "_ConceptualTOC_.xml");
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Create the Sandcastle configuration file
                this.ReportProgress(BuildStep.CreateBuildAssemblerConfigs, "Creating Sandcastle configuration files...");

                // Add referenced namespaces to the hash set.  These are used to ensure just the needed set of
                // reflection target files are loaded by BuildAssembler and nothing more to save some time and
                // memory.
                var rn = this.ReferencedNamespaces;

                // These are all of the valid namespaces we are interested in.  This prevents the methods below
                // from returning nested types as potential namespaces since they can't tell the difference.
                HashSet<string> validNamespaces = new HashSet<string>(Directory.EnumerateFiles(
                    this.FrameworkReflectionDataFolder, "*.xml", SearchOption.AllDirectories).Select(
                        f => Path.GetFileNameWithoutExtension(f)));

                // Get namespaces referenced in the XML comments of the documentation sources
                foreach(var n in commentsFiles.GetReferencedNamespaces(validNamespaces))
                    rn.Add(n);

                // Get namespaces referenced in the reflection data (plug-ins are responsible for adding
                // additional namespaces if they add other reflection data files).
                foreach(string n in GetReferencedNamespaces(reflectionFile, validNamespaces))
                    rn.Add(n);

                // Get namespaces from the Framework comments files of the referenced namespaces.  This adds
                // references for stuff like designer and support classes not directly referenced anywhere else.
                foreach(string n in frameworkReflectionData.GetReferencedNamespaces(language, rn, validNamespaces).ToList())
                    rn.Add(n);

                // If F# syntax is being generated, add some of the F# namespaces as the syntax sections generate
                // references to types that may not be there in non-F# projects.
                if(ComponentUtilities.SyntaxFiltersFrom(syntaxGenerators, project.SyntaxFilters).Any(
                  f => f.Id == "F#"))
                {
                    rn.Add("Microsoft.FSharp.Core");
                    rn.Add("Microsoft.FSharp.Control");
                }

                // If there are no referenced namespaces, add System as a default to prevent the build components
                // from loading the entire set.
                if(rn.Count == 0)
                    rn.Add("System");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    this.ExecutePlugIns(ExecutionBehaviors.Before);

                    this.ReportProgress("    sandcastle.config");

                    // The configuration varies based on the style.  We'll use a common name (sandcastle.config).
                    resolvedPath = presentationStyle.ResolvePath(presentationStyle.ReferenceBuildConfiguration);
                    substitutionTags.TransformTemplate(Path.GetFileName(resolvedPath), Path.GetDirectoryName(resolvedPath),
                        workingFolder);

                    if(!Path.GetFileName(resolvedPath).Equals("sandcastle.config", StringComparison.OrdinalIgnoreCase))
                        File.Move(workingFolder + Path.GetFileName(resolvedPath), workingFolder + "sandcastle.config");

                    // The conceptual content configuration file is only created if needed.
                    if(this.ConceptualContent.ContentLayoutFiles.Count != 0)
                    {
                        this.ReportProgress("    conceptual.config");

                        resolvedPath = presentationStyle.ResolvePath(presentationStyle.ConceptualBuildConfiguration);

                        substitutionTags.TransformTemplate(Path.GetFileName(resolvedPath), Path.GetDirectoryName(resolvedPath),
                            workingFolder);

                        if(!Path.GetFileName(resolvedPath).Equals("conceptual.config", StringComparison.OrdinalIgnoreCase))
                            File.Move(workingFolder + Path.GetFileName(resolvedPath), workingFolder + "conceptual.config");
                    }

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Merge the build component custom configurations
                this.MergeComponentConfigurations();

                commentsFiles = null;

                // Build the conceptual help topics
                if(this.ConceptualContent.ContentLayoutFiles.Count != 0)
                {
                    this.ReportProgress(BuildStep.BuildConceptualTopics, "Building conceptual help topics...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("BuildConceptualTopics.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildConceptualTopics.proj", false);
                        
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // Build the reference help topics
                this.ReportProgress(BuildStep.BuildReferenceTopics, "Building reference help topics...");

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    scriptFile = substitutionTags.TransformTemplate("BuildReferenceTopics.proj", templateFolder,
                        workingFolder);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);
                                        
                    taskRunner.RunProject("BuildReferenceTopics.proj", false);
                    
                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Combine the conceptual and API intermediate TOC files into one
                this.CombineIntermediateTocFiles();

                // The last part differs based on the help file format
                if((project.HelpFileFormat & (HelpFileFormats.HtmlHelp1 | HelpFileFormats.Website)) != 0)
                {
                    this.ReportProgress(BuildStep.ExtractingHtmlInfo,
                        "Extracting HTML info for HTML Help 1 and/or website...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("ExtractHtmlInfo.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("ExtractHtmlInfo.proj", true);

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // Copy the standard help file content.  This is done just before compiling the help so that
                // template files from the presentation style can take advantage of tag substitution.  By this
                // point, we should have everything we could possibly need.
                this.CopyStandardHelpContent();

                if((project.HelpFileFormat & HelpFileFormats.HtmlHelp1) != 0)
                {
                    // Generate the table of contents and set the default topic
                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents,
                        "Generating HTML Help 1 table of contents file...");

                    currentFormat = HelpFileFormats.HtmlHelp1;

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        // It got created in the ExtractingHtmlInfo step above
                        // so there is actually nothing to do here.

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Generate the help file index
                    this.ReportProgress(BuildStep.GenerateHelpFileIndex, "Generating HTML Help 1 index file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        // It got created in the ExtractingHtmlInfo step above
                        // so there is actually nothing to do here.

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Generate the help project file
                    this.ReportProgress(BuildStep.GenerateHelpProject, "Generating HTML Help 1 project file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        substitutionTags.TransformTemplate("Help1x.hhp", templateFolder, workingFolder);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Build the HTML Help 1 help file
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Compiling HTML Help 1 file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("Build1xHelpFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("Build1xHelpFile.proj", true);
                        
                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.MSHelpViewer) != 0)
                {
                    // The following build steps are executed to allow plug-ins to handle any necessary processing
                    // but nothing actually happens here:
                    //
                    //      BuildStep.GenerateHelpFormatTableOfContents
                    //      BuildStep.GenerateHelpProject
                    //
                    // For the MS Help Viewer format, there is no project file to compile and the TOC layout is
                    // generated when the help file is ultimately installed using metadata within each topic file.
                    // All of the necessary TOC info is stored in the intermediate TOC file generated prior to
                    // building the topics.  The BuildAssembler MSHCComponent inserts the TOC info into each topic
                    // as it is built.

                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents,
                        "Executing informational Generate Table of Contents " +
                        "build step for plug-ins (not used for MS Help Viewer)");

                    currentFormat = HelpFileFormats.MSHelpViewer;

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    this.ReportProgress(BuildStep.GenerateHelpProject,
                        "Executing informational Generate Help Project " +
                        "build step for plug-ins (not used for MS Help Viewer)");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Build the MS Help Viewer help file
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Generating MS Help Viewer file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        substitutionTags.TransformTemplate("HelpContentSetup.msha", templateFolder, workingFolder);

                        // Rename the content setup file to use the help filename to keep them related and
                        // so that multiple output files can be sent to the same output folder.
                        File.Move(workingFolder + "HelpContentSetup.msha", workingFolder + this.ResolvedHtmlHelpName + ".msha");

                        // Generate the example install and remove scripts
                        substitutionTags.TransformTemplate("InstallMSHC.bat", templateFolder, workingFolder);
                        File.Move(workingFolder + "InstallMSHC.bat", workingFolder + "Install_" +
                            this.ResolvedHtmlHelpName + ".bat");

                        substitutionTags.TransformTemplate("RemoveMSHC.bat", templateFolder, workingFolder);
                        File.Move(workingFolder + "RemoveMSHC.bat", workingFolder + "Remove_" +
                            this.ResolvedHtmlHelpName + ".bat");

                        // Copy the launcher utility
                        File.Copy(ComponentUtilities.ToolsFolder + "HelpLibraryManagerLauncher.exe",
                            workingFolder + "HelpLibraryManagerLauncher.exe");
                        File.SetAttributes(workingFolder + "HelpLibraryManagerLauncher.exe", FileAttributes.Normal);

                        scriptFile = substitutionTags.TransformTemplate("BuildHelpViewerFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildHelpViewerFile.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.Website) != 0)
                {
                    // Generate the table of contents and set the default topic
                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents,
                        "Generating website table of contents file...");

                    currentFormat = HelpFileFormats.Website;

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        // It got created in the ExtractingHtmlInfo step above
                        // so there is actually nothing to do here.

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    this.GenerateWebsite();
                }

                if((project.HelpFileFormat & HelpFileFormats.OpenXml) != 0)
                {
                    // The following build steps are executed to allow plug-ins to handle any necessary processing
                    // but nothing actually happens here:
                    //
                    //      BuildStep.GenerateHelpFormatTableOfContents
                    //      BuildStep.GenerateHelpProject
                    //
                    // For the Open XML format, there is no project file to compile and the TOC layout is
                    // generated when the document is opened.  All of the necessary TOC info is stored in the
                    // intermediate TOC file generated prior to building the topics.  The process used to merge
                    // the topics into a single document uses it to define the order in which the topics are
                    // combined.

                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Executing informational " +
                        "Generate Table of Contents build step for plug-ins (not used for Open XML)");

                    currentFormat = HelpFileFormats.OpenXml;

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    this.ReportProgress(BuildStep.GenerateHelpProject, "Executing informational Generate Help " +
                        "Project build step for plug-ins (not used for Open XML)");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Build the Open XML document
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Generating Open XML document file...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("BuildOpenXmlFile.proj", templateFolder,
                            workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("BuildOpenXmlFile.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                if((project.HelpFileFormat & HelpFileFormats.Markdown) != 0)
                {
                    // The following build steps are executed to allow plug-ins to handle any necessary processing
                    // but nothing actually happens here:
                    //
                    //      BuildStep.GenerateHelpFormatTableOfContents
                    //      BuildStep.GenerateHelpProject
                    //
                    // For the Markdown format, there is no project file to compile and the TOC layout is
                    // generated by the build task.  All of the necessary TOC info is stored in the intermediate
                    // TOC file generated prior to building the topics.  The build task uses it to find the
                    // topics to finalize and generate the sidebar TOC file.
                    this.ReportProgress(BuildStep.GenerateHelpFormatTableOfContents, "Executing informational " +
                        "Generate Table of Contents build step for plug-ins (not used for Markdown)");

                    currentFormat = HelpFileFormats.Markdown;

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    this.ReportProgress(BuildStep.GenerateHelpProject, "Executing informational Generate Help " +
                        "Project build step for plug-ins (not used for Markdown)");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }

                    // Generate the markdown content
                    this.ReportProgress(BuildStep.CompilingHelpFile, "Generating markdown content...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        scriptFile = substitutionTags.TransformTemplate("GenerateMarkdownContent.proj",
                            templateFolder, workingFolder);

                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        taskRunner.RunProject("GenerateMarkdownContent.proj", true);

                        this.GatherBuildOutputFilenames();
                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }

                // All done
                if(project.CleanIntermediates)
                {
                    this.ReportProgress(BuildStep.CleanIntermediates, "Removing intermediate files...");

                    if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                    {
                        this.ExecutePlugIns(ExecutionBehaviors.Before);

                        try
                        {
                            Directory.Delete(workingFolder, true);
                        }
                        catch(IOException ioEx)
                        {
                            this.ReportProgress("    Not all build output was removed from '{0}': {1}",
                                workingFolder, ioEx.Message);
                        }
                        catch(UnauthorizedAccessException uaEx)
                        {
                            this.ReportProgress("    Not all build output was removed from '{0}': {1}",
                                workingFolder, uaEx.Message);
                        }

                        this.ExecutePlugIns(ExecutionBehaviors.After);
                    }
                }
AllDone:
                TimeSpan runtime = DateTime.Now - buildStart;

                this.ReportProgress(BuildStep.Completed, "\r\nBuild completed successfully at {0}.  " +
                    "Total time: {1:00}:{2:00}:{3:00.0000}\r\n", DateTime.Now, Math.Floor(runtime.TotalSeconds / 3600),
                    Math.Floor((runtime.TotalSeconds % 3600) / 60), (runtime.TotalSeconds % 60));

                System.Diagnostics.Debug.WriteLine("Build process finished successfully\r\n");
            }
            catch(OperationCanceledException )
            {
                buildCancelling = true;

                this.ReportError(BuildStep.Canceled, "BE0064", "BUILD CANCELLED BY USER");

                System.Diagnostics.Debug.WriteLine("Build process aborted\r\n");
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);

                var agEx = ex as AggregateException;

                if(agEx != null)
                    foreach(var inEx in agEx.InnerExceptions)
                    {
                        if(message != null)
                            message += "\r\n\r\n";

                        message += inEx.Message + "\r\n" + inEx.StackTrace;
                    }

                var bex = ex as BuilderException;

                do
                {
                    if(message != null)
                        message += "\r\n\r\n";

                    message += ex.Message + "\r\n" + ex.StackTrace;
                    ex = ex.InnerException;

                } while(ex != null);

                // NOTE: Message may contain format markers so pass it as a format argument
                if(bex != null)
                    this.ReportError(BuildStep.Failed, bex.ErrorCode, "{0}", message);
                else
                    this.ReportError(BuildStep.Failed, "BE0065", "BUILD FAILED: {0}", message);

                System.Diagnostics.Debug.WriteLine("Build process failed\r\n");
            }
            finally
            {
                try
                {
                    this.ExecutePlugIns(ExecutionBehaviors.Before);
                }
                catch(Exception ex)
                {
                    // Not much we can do at this point...
                    this.ReportProgress(ex.ToString());
                }

                try
                {
                    this.ExecutePlugIns(ExecutionBehaviors.After);

                    if(componentContainer != null)
                        componentContainer.Dispose();
                }
                catch(Exception ex)
                {
                    // Not much we can do at this point...
                    this.ReportProgress(ex.ToString());
                }
                finally
                {
                    if(swLog != null)
                    {
                        swLog.WriteLine("</buildStep>\r\n</shfbBuild>");
                        swLog.Close();
                        swLog = null;
                    }

                    // If we created a copy of the project, dispose of it and return to the original
                    if(originalProject != null)
                    {
                        project.Dispose();
                        project = originalProject;
                    }

                    if(this.CurrentBuildStep == BuildStep.Completed && !project.KeepLogFile)
                        File.Delete(this.LogFilename);
                }
            }
        }
Exemplo n.º 33
0
        static void Main()
        {
            // It's important to call these before starting the app; otherwise theming and bitmaps
            //  may not render correctly.
            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());

            // Register the embedded image resources so that they will be available for all users of ResourceUtil,
            //  such as the PaletteService.
            ResourceUtil.Register(typeof(Resources));

            // enable metadata driven property editing
            DomNodeType.BaseOfAllTypes.AddAdapterCreator(new AdapterCreator<CustomTypeDescriptorNodeAdapter>());

            var catalog = new TypeCatalog(
                typeof(SettingsService),                // persistent settings and user preferences dialog
                typeof(StatusService),                  // status bar at bottom of main Form
                typeof(LiveConnectService),             // allows easy interop between apps on same router subnet
                typeof(Outputs),                        // passes messages to all IOutputWriter components
                typeof(OutputService),                  // rich text box for displaying error and warning messages. Implements IOutputWriter
                typeof(CommandService),                 // handles commands in menus and toolbars
                typeof(ControlHostService),             // docking control host
                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(FileDialogService),              // standard Windows file dialogs
                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                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(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(StandardEditCommands),           // standard Edit menu commands for copy/paste
                typeof(StandardEditHistoryCommands),    // standard Edit menu commands for undo/redo
                typeof(StandardSelectionCommands),      // standard Edit menu selection commands
                typeof(RenameCommand),                  // allows for renaming of multiple selected objects
                
                //StandardPrintCommands does not currently work with Direct2D
                //typeof(StandardPrintCommands),        // standard File menu print commands

                typeof(PaletteService),                 // global palette, for drag/drop instancing
                typeof(PropertyEditor),                 // property grid for editing selected objects
                typeof(GridPropertyEditor),             // grid control for editing selected objects
                typeof(PropertyEditingCommands),        // commands for PropertyEditor and GridPropertyEditor
                typeof(PerformanceMonitor),             // displays the frame rate and memory usage
                typeof(FileWatcherService),                // service to watch for changes to files
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                typeof(SkinService),                    // allows for customization of an application’s appearance by using inheritable properties that can be applied at run-time
                
                // Client-specific plug-ins
                typeof(TimelineEditor),                 // timeline editor component
                typeof(TimelineCommands),               // defines Timeline-specific commands
                typeof(HelpAboutCommand),               // Help -> About command

                // Testing related
                typeof(PythonService),                  // scripting service for automated tests
                typeof(ScriptConsole),                  // provides a dockable command console for entering Python commands
                typeof(AtfScriptVariables),             // exposes common ATF services as script variables
                typeof(AutomationService)               // provides facilities to run an automated script using the .NET remoting service
                );
            
            var container = new CompositionContainer(catalog);

            var toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;

            var mainForm = new MainForm(toolStripContainer)
            {
                Text = "Timeline Editor Sample".Localize(),
                Icon = GdiUtil.CreateIcon(ResourceUtil.GetImage(Sce.Atf.Resources.AtfIconImage))
            };

            var batch = new CompositionBatch();
            batch.AddPart(mainForm);
            batch.AddPart(new WebHelpCommands("https://github.com/SonyWWS/ATF/wiki/ATF-Timeline-Editor-Sample".Localize()));

            container.Compose(batch);

            // 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();
        }
Exemplo n.º 34
0
        /// <summary>
        /// 组合部件
        /// </summary>
        private void Compose()
        {
            //判断Plugins文件夹是否存在
            if (!Directory.Exists("Plugins"))
            {
                Directory.CreateDirectory("Plugins");
            }

            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog("Plugins"));
            _container = new CompositionContainer(catalog);
            try
            {
                _container.ComposeParts(_pluginsImport);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                _container.Dispose();
            }
        }