//[ImportMany(typeof(IFormExstension), AllowRecomposition = true)] //public List<IFormExstension> FormExtensions { get; set; } public void LoadExtensions() { string path = Application.StartupPath + @"\Extensions"; if(Directory.Exists(path)) { var catalog = new AggregateCatalog( new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog(path)); var batch = new CompositionBatch(); batch.AddPart(this); _container = new CompositionContainer(catalog); try { _container.Compose(batch); } catch (CompositionException compositionException) { MessageBox.Show(compositionException.ToString()); } } }
internal static CompositionContainer GetCompositionContainer(Assembly assembly, CompositionBatch batch) { var assemblyLocation = assembly.Location; var file = new FileInfo(assemblyLocation); var catalogs = new List <ComposablePartCatalog> { new AssemblyCatalog(assembly), new DirectoryCatalog(file.DirectoryName ?? ".") }; var catalog = new AggregateCatalog(catalogs); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); batch.AddExportedValue(container); container.Compose(batch); return(container); }
static void Main() { double start = LevelEditorCore.Timing.GetHiResCurrentTime(); #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.DesignViewSettings), typeof(LevelEditorCore.ResourceLister), typeof(LevelEditorCore.ThumbnailService), typeof(LevelEditorCore.ResourceMetadataEditor), typeof(LevelEditorCore.LayerLister), typeof(LevelEditorCore.ResourceConverterService), typeof(LevelEditorCore.Commands.PickFilterCommands), typeof(LevelEditorCore.Commands.DesignViewCommands), typeof(LevelEditorCore.Commands.ManipulatorCommands), typeof(LevelEditorCore.Commands.ShowCommands), typeof(LevelEditorCore.Commands.GroupCommands), typeof(LevelEditorCore.Commands.CameraCommands), typeof(LevelEditorCore.MayaStyleCameraController), typeof(LevelEditorCore.ArcBallCameraController), typeof(LevelEditorCore.WalkCameraController), typeof(LevelEditorCore.FlyCameraController) ); TypeCatalog thisAssemCatalog = new TypeCatalog( typeof(LevelEditor.GameLoopService), 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.GameEngine), 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)); } // load all dlls in \MEFPlugin string mefpluginDir = pluginDir + "\\MEFPlugin"; if (Directory.Exists(mefpluginDir)) { var filepaths = Directory.GetFiles(mefpluginDir).Where(path => path.EndsWith(".dll")); foreach (var filepath in filepaths) { Assembly filepathAssembly = Assembly.LoadFrom(filepath); catalogs.Add(new AssemblyCatalog(filepathAssembly)); } } 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 var gameEngine = container.GetExportedValue <IGameEngineProxy>(); foreach (IInitializable initializable in container.GetExportedValues <IInitializable>()) { initializable.Initialize(); } GC.KeepAlive(gameEngine); 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(); GC.KeepAlive(start); }
/// <summary> /// By default, we are configured to use MEF /// </summary> protected override void Configure() { try { var splashScreen = new SplashScreen(Assembly.GetAssembly(typeof(AppBootstrapper)), "daxstudio-splash.png"); splashScreen.Show(true); // Tell Caliburn Micro how to find controls in Fluent Ribbon /* * defaultElementLookup = BindingScope.GetNamedElements; * BindingScope.GetNamedElements = new Func<System.Windows.DependencyObject, IEnumerable<System.Windows.FrameworkElement>>( * k => * { * List<FrameworkElement> namedElements = new List<FrameworkElement>(); * namedElements.AddRange(defaultElementLookup(k)); * Fluent.Ribbon ribbon = LookForRibbon(k); * if (null != ribbon) * AppendRibbonNamedItem(ribbon, namedElements); * return namedElements; * } * ); */ ConventionManager.AddElementConvention <Fluent.Spinner>(Fluent.Spinner.ValueProperty, "Value", "ValueChanged"); ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.DoubleUpDown>(Xceed.Wpf.Toolkit.DoubleUpDown.ValueProperty, "Value", "ValueChanged"); ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.IntegerUpDown>(Xceed.Wpf.Toolkit.IntegerUpDown.ValueProperty, "Value", "ValueChanged"); ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.WatermarkTextBox>(Xceed.Wpf.Toolkit.WatermarkTextBox.TextProperty, "Text", "TextChanged"); // Fixes the default datetime format in the results listview // from: http://stackoverflow.com/questions/1993046/datetime-region-specific-formatting-in-wpf-listview FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); var catalog = new AggregateCatalog( AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>() ); //_container = new CompositionContainer(catalog,true); _container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddExportedValue <IWindowManager>(new WindowManager()); batch.AddExportedValue <IEventAggregator>(new EventAggregator()); batch.AddExportedValue <Func <DocumentViewModel> >(() => _container.GetExportedValue <DocumentViewModel>()); batch.AddExportedValue <Func <IWindowManager, IEventAggregator, DocumentViewModel> >( (w, e) => _container.GetExportedValue <DocumentViewModel>()); batch.AddExportedValue(_container); batch.AddExportedValue(catalog); _container.Compose(batch); // Add AvalonDock binding convetions AvalonDockConventions.Install(); ConfigureKeyBindings(); // TODO - not working //VisibilityBindingConvention.Install(); LogManager.GetLog = type => new DebugLogger(type); } catch (Exception e) { Debug.WriteLine(e); } }
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(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), // vistual 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(DiagramTheme), // rendering theme for diagrams 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()) { 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(); }
/// <summary> /// 注入WindowManager /// </summary> /// <param name="batch"></param> protected virtual void InjectWindowManager(CompositionBatch batch) { batch.AddExportedValue <IWindowManager>(new WindowManager()); }
public MefSubstituteBuilder() { _batch = new CompositionBatch(); _types = new HashSet <Type>(); }
public void Compose(CompositionBatch batch) { batch.AddExportedValue <IPerceptualHash>(new AForgePerceptualHash()); batch.AddExportedValue <ITemplateMatcher>(new Matcher()); batch.AddExportedValue <ICornerDetector>(new CornerDetector()); }
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(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(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 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 = "RobotDirector".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(); }
protected virtual void ConfigureContainer(CompositionBatch builder) { }
public void Compose(CompositionBatch batch) { tasks.Apply(s => s.Compose(batch)); }
protected override void InjectWindowManager(CompositionBatch batch) { base.InjectWindowManager(batch); batch.AddExportedValue <IMetroWindowManager>(new MetroWindowManager()); }
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(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), // 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(SkinService), 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(); }
/// <summary> /// By default, we are configured to use MEF /// </summary> protected override void Configure() { MessageBinder.SpecialValues.Add("$scaledmousex", (ctx) => { var img = ctx.Source as Image; var input = ctx.Source as IInputElement; var e = ctx.EventArgs as MouseEventArgs; //// If there is an image control, get the scaled position if (img != null && e != null) { Point position = e.GetPosition(img); return((int)(img.Source.Width * (position.X / img.ActualWidth))); } // If there is another type of of IInputControl get the non-scaled position - or do some processing to get a scaled position, whatever needs to happen if (e != null && input != null) { return(e.GetPosition(input).X); } // Return 0 if no processing could be done return(0); }); MessageBinder.SpecialValues.Add("$scaledmousey", (ctx) => { var img = ctx.Source as Image; var input = ctx.Source as IInputElement; var e = ctx.EventArgs as MouseEventArgs; // If there is an image control, get the scaled position if (img != null && e != null) { Point position = e.GetPosition(img); return((int)(img.Source.Height * (position.Y / img.ActualHeight))); } // If there is another type of of IInputControl get the non-scaled position - or do some processing to get a scaled position, whatever needs to happen if (e != null && input != null) { return(e.GetPosition(input).Y); } // Return 0 if no processing could be done return(0); }); // Add all assemblies to AssemblySource (using a temporary DirectoryCatalog). var directoryCatalog = new DirectoryCatalog(@"./"); try { AssemblySource.Instance.AddRange( directoryCatalog.Parts .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly) .Where(assembly => !AssemblySource.Instance.Contains(assembly))); } catch (Exception ex) { if (ex is System.Reflection.ReflectionTypeLoadException) { var typeLoadException = ex as ReflectionTypeLoadException; var loaderExceptions = typeLoadException.LoaderExceptions; } } // Prioritise the executable assembly. This allows the client project to override exports, including IShell. // The client project can override SelectAssemblies to choose which assemblies are prioritised. _priorityAssemblies = SelectAssemblies().ToList(); var priorityCatalog = new AggregateCatalog(_priorityAssemblies.Select(x => new AssemblyCatalog(x))); var priorityProvider = new CatalogExportProvider(priorityCatalog); // Now get all other assemblies (excluding the priority assemblies). var mainCatalog = new AggregateCatalog( AssemblySource.Instance .Where(assembly => !_priorityAssemblies.Contains(assembly)) .Select(x => new AssemblyCatalog(x))); var mainProvider = new CatalogExportProvider(mainCatalog); Container = new CompositionContainer(priorityProvider, mainProvider); priorityProvider.SourceProvider = Container; mainProvider.SourceProvider = Container; var batch = new CompositionBatch(); BindServices(batch); batch.AddExportedValue(mainCatalog); Container.Compose(batch); }
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 }
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 Engine engine = new Engine(); engine.StartEngine("TongCompiler", null); // 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(UnhandledExceptionService), // catches unhandled exceptions, displays info, and gives user a chance to save typeof(FileDialogService), // standard Windows file dialogs typeof(DomNodeRefDictionary), // Reference dictionary typeof(TongScriptCompilerTypeManager), typeof(ScriptNodeDefinitionManager), //typeof(ZooKeeperSession), typeof(TongCompilerStart), typeof(TongCompilerBatchRead), typeof(TongCompilerBatchGenerateBytecode), typeof(Outputs), // passes messages to all log writers typeof(ErrorDialogService), // displays errors to the user in a message box typeof(ConsoleOutputWriter) ); // enable use of the system clipboard StandardEditCommands.UseSystemClipboard = true; // Set up the MEF container with these components var container = new CompositionContainer(catalog); // Configure the main Form var batch = new CompositionBatch(); var mainForm = new ConsoleMainForm() { Text = Application.ProductName, }; // Add the main Form instance, etc., to the container batch.AddPart(mainForm); container.Compose(batch); container.InitializeAll(); mainForm.Run(); mainForm.Close(); // Give components a chance to clean up. container.Dispose(); engine.StopEngine(); }
public static CompositionBatch AddValue <TContract>(this CompositionBatch batch, TContract value) { string contractName = AttributedModelServices.GetContractName(typeof(TContract)); return(batch.AddValue(contractName, value)); }
public void Compose(CompositionBatch batch) { Container.Compose(batch); }
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(); }
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(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 #if !DEBUG typeof(CrashLogger), // logs unhandled exceptions to an ATF server typeof(UnhandledExceptionService), // catches unhandled exceptions, displays info, and gives user a chance to save #endif typeof(DomExplorer), //Debug view the DOM 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(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(HelpAboutCommand), // Help -> About command typeof(PropertyEditor), // property grid 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(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 //Worldsmith stuff typeof(SchemaLoader), //Loads the schema typeof(Project.DotaVPKService), //Handles the VPK stuff, including reading from the VPK and building the DOM node //UI Elements typeof(ProjectTreeLister), typeof(UnitTreeLister), typeof(TextEditing.TextEditor), typeof(DotaVPKTreeLister), typeof(KeyValueEditor), // typeof(UnitPropertyEditor), //Commands typeof(ProjectCommands), typeof(TreeListCommands), typeof(KeyValueCommands) ); // Set up the MEF container with these components var container = new CompositionContainer(catalog); // Configure the main Form var batch = new CompositionBatch(); var toolStripContainer = new ToolStripContainer(); var mainForm = new MainForm(toolStripContainer) { Text = "Worldsmith".Localize(), Icon = GdiUtil.CreateIcon(WorldsmithATF.Properties.Resources.WSIcon32) }; // Add the main Form instance to the container batch.AddPart(mainForm); batch.AddPart(new WebHelpCommands("http://www.worldsmith.net".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(); }
/// <summary> /// Do the composition /// </summary> /// <param name="re"></param> public static void Compose <T>(T re) { _batch.AddPart(re); _container.Compose(_batch); _batch = new CompositionBatch(); }
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(); }
private void BindServices(CompositionBatch batch) { batch.AddExportedValue <IWindowManager>(new WindowManager()); }
protected virtual void BindServices(CompositionBatch batch) { batch.AddExportedValue <IWindowManager>(new WindowManager()); batch.AddExportedValue <IEventAggregator>(new EventAggregator()); batch.AddExportedValue(_container); }
protected virtual void PrepareCompositionContainer(CompositionBatch batch) { }
static void Main(string[] arg) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture; // For testing localization //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ja"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.DoEvents(); ShowBitNess(); ISledCrashReporter crashReporter = null; ISledUsageStatistics usageStatistics = null; try { // Try and create crash reporter crashReporter = SledLibCrashReportNetWrapper.TryCreateCrashReporter(); // Try and create usage statistics usageStatistics = SledLibCrashReportNetWrapper.TryCreateUsageStatistics(); // Create 'master' catalog to hold all // other catalogs we might create var aggregateCatalog = new AggregateCatalog(); // Add 'standard/default' parts to 'master' catalog aggregateCatalog.Catalogs.Add( new TypeCatalog( /* ATF related services */ typeof(SettingsService), typeof(StatusService), typeof(CommandService), typeof(ControlHostService), typeof(UnhandledExceptionService), typeof(UserFeedbackService), typeof(OutputService), typeof(Outputs), typeof(FileDialogService), typeof(DocumentRegistry), typeof(ContextRegistry), typeof(StandardFileExitCommand), typeof(RecentDocumentCommands), typeof(StandardEditCommands), typeof(StandardEditHistoryCommands), typeof(TabbedControlSelector), typeof(DefaultTabCommands), typeof(WindowLayoutService), typeof(WindowLayoutServiceCommands), typeof(SkinService), /* SLED related services */ typeof(SledOutDevice), typeof(SledAboutService), typeof(SledAboutDocumentService), typeof(SledGotoService), typeof(SledTitleBarTextService), typeof(SledDocumentService), typeof(SledProjectService), typeof(SledProjectWatcherService), typeof(SledModifiedProjectFormService), typeof(SledProjectFileGathererService), typeof(SledLanguageParserService), typeof(SledProjectFilesTreeEditor), typeof(SledProjectFilesDiskViewEditor), typeof(SledProjectFileFinderService), typeof(SledProjectFilesUtilityService), typeof(SledProjectFileAdderService), typeof(SledBreakpointService), typeof(SledBreakpointEditor), typeof(SledNetworkPluginService), typeof(SledLanguagePluginService), typeof(SledTargetService), typeof(SledFindAndReplaceService), typeof(SledFindAndReplaceService.SledFindResultsEditor1), typeof(SledFindAndReplaceService.SledFindResultsEditor2), typeof(SledDebugService), typeof(SledDebugScriptCacheService), typeof(SledDebugBreakpointService), typeof(SledDebugFileService), typeof(SledDebugHeartbeatService), typeof(SledDebugNegotiationTimeoutService), typeof(SledDebugFlashWindowService), typeof(SledFileWatcherService), typeof(SledModifiedFilesFormService), typeof(SledFileExtensionService), typeof(SledSyntaxCheckerService), typeof(SledSyntaxErrorsEditor), typeof(SledTtyService), typeof(SledDebugFreezeService), typeof(SledSourceControlService), typeof(SledSharedSchemaLoader) )); // Create directory information service var directoryInfoService = new SledDirectoryInfoService(); // Create dynamic plugin service var dynamicPluginService = new SledDynamicPluginService(); // Grab all dynamically loaded plugins // from the "SLED\Plugins" directory var dynamicAssemblies = dynamicPluginService.GetDynamicAssemblies(directoryInfoService); // Add dynamically obtained assemblies to // the master catalog AddAssembliesToMasterCatalog(aggregateCatalog, dynamicAssemblies); // Add 'master' catalog to container using (var container = new CompositionContainer(aggregateCatalog)) { // Create tool strip container using (var toolStripContainer = new ToolStripContainer()) { toolStripContainer.Dock = DockStyle.Fill; // Grab SledShared.dll for resource loading var assem = Assembly.GetAssembly(typeof(SledShared)); // Create main form & set up some properties var mainForm = new MainForm(toolStripContainer) { AllowDrop = true, Text = Resources.Resource.SLED, Icon = GdiUtil.GetIcon( assem, SledShared.IconPathBase + ".Sled.ico") }; // Load all the icons and images SLED will need SledShared.RegisterImages(); directoryInfoService.MainForm = mainForm; // Create batch and add any manual parts var batch = new CompositionBatch(); batch.AddPart(mainForm); batch.AddPart(directoryInfoService); batch.AddPart(dynamicPluginService); SetupDebugEventFiringWatching(batch); container.Compose(batch); // Set this one time SledServiceReferenceCompositionContainer.SetCompositionContainer(container); // Initialize all IInitializable interfaces try { try { foreach (var initializable in container.GetExportedValues <IInitializable>()) { initializable.Initialize(); } } catch (CompositionException ex) { foreach (var error in ex.Errors) { MessageBox.Show(error.Description, MefCompositionExceptionText); } throw; } } catch (Exception ex) { MessageBox.Show(ex.ToString(), ExceptionDetailsText); Environment.Exit(-1); } // Send usage data to the server now that everything is loaded if (usageStatistics != null) { usageStatistics.PhoneHome(); } SledOutDevice.OutBreak(); // Notify directoryInfoService.LoadingFinished(); // Let ATF's UnhandledExceptionService know about our ICrashLogger if (crashReporter != null) { var unhandledExceptionService = SledServiceInstance.TryGet <UnhandledExceptionService>(); if (unhandledExceptionService != null) { unhandledExceptionService.CrashLogger = crashReporter; } } // Show main form finally Application.Run(mainForm); } } } finally { // // Cleanup // if (crashReporter != null) { crashReporter.Dispose(); } if (usageStatistics != null) { usageStatistics.Dispose(); } } }
private void InitializeSecurityContext(StubNavigationService navigationService, out IMenuDefinition[] menus, out ISubMenuDefinition[] subMenus, out IServiceBus serviceBus) { // N'importer que les IMenuDefinition et ISubMenuDefinition var menuDeftype = typeof(IMenuDefinition); var subMenuDeftype = typeof(ISubMenuDefinition); var assembly = typeof(KProcess.Ksmed.Presentation.Shell.Controller).Assembly; // Rechercher les types qui les implémentent var menuTypes = assembly.GetTypes().Where(t => t.GetInterface(menuDeftype.FullName) != null || t.GetInterface(subMenuDeftype.FullName) != null).ToArray(); // Composer MEF var container = new CompositionContainer( new AggregateCatalog( new TypeCatalog(menuTypes), new TypeCatalog( typeof(IServiceBus), typeof(ServiceBus), typeof(IEventBus), typeof(EventBus) ))); CompositionBatch batch = new CompositionBatch(); batch.AddPart(this); batch.AddExportedValue<CompositionContainer>(container); //IoC.RegisterInstance<CompositionContainer>(_container); container.Compose(batch); menus = container.GetExports<IMenuDefinition>().Select(l => l.Value).ToArray(); subMenus = container.GetExports<ISubMenuDefinition>().Select(l => l.Value).ToArray(); foreach (var menu in menus) { menu.Initialize(); } var rolesReadAuthorizations = new Dictionary<Type, string[]>(); var rolesWriteAuthorizations = new Dictionary<Type, string[]>(); var featuresReadAuthorizations = new Dictionary<Type, short[]>(); var featuresWriteAuthorizations = new Dictionary<Type, short[]>(); var customReadAuthorizations = new Dictionary<Type, Func<string, bool>>(); var customWriteAuthorizations = new Dictionary<Type, Func<string, bool>>(); var accessProjectContext = new Dictionary<Type, bool>(); foreach (var subMenu in subMenus) { subMenu.Initialize(); rolesReadAuthorizations[subMenu.ViewModelType] = subMenu.RolesCanRead; rolesWriteAuthorizations[subMenu.ViewModelType] = subMenu.RolesCanWrite; featuresReadAuthorizations[subMenu.ViewModelType] = subMenu.FeaturesCanRead; featuresWriteAuthorizations[subMenu.ViewModelType] = subMenu.FeaturesCanWrite; customReadAuthorizations[subMenu.ViewModelType] = subMenu.CustomCanRead; customWriteAuthorizations[subMenu.ViewModelType] = subMenu.CustomCanWrite; accessProjectContext[subMenu.ViewModelType] = subMenu.IsSecurityProjectContext; } Security.SecurityContext.RegisterAuthorizations( rolesReadAuthorizations, rolesWriteAuthorizations, featuresReadAuthorizations, featuresWriteAuthorizations, customReadAuthorizations, customWriteAuthorizations); serviceBus = container.GetExport<IServiceBus>().Value; serviceBus.Register<INavigationService>(navigationService); serviceBus.Register<IProjectManagerService>(new StubProjectManagerService()); }
static SharedProjectTest() { var runningLoc = Path.GetDirectoryName(typeof(SharedProjectTest).Assembly.Location); // we want to pick up all of the MEF exports which are available, but they don't // depend upon us. So if we're just running some tests in the IDE when the deployment // happens it won't have the DLLS with the MEF exports. So we copy them here. if (!CommonUtils.IsSameDirectory(typeof(SharedProjectTest).Assembly.Location, TestData.BinarySourceLocation)) { foreach (var file in Directory.GetFiles(TestData.BinarySourceLocation, "*.dll")) { try { File.Copy(file, Path.Combine(runningLoc, Path.GetFileName(file)), true); } catch { // some of our DLLs our in use because we're running... } } } // load all of the available DLLs that depend upon TestUtilities into our catalog List <AssemblyCatalog> catalogs = new List <AssemblyCatalog>(); foreach (var file in Directory.GetFiles(runningLoc, "*.dll")) { TryAddAssembly(catalogs, file); } // Compose everything var catalog = new AggregateCatalog(catalogs.ToArray()); var container = Container = new CompositionContainer(catalog); var compBatch = new CompositionBatch(); container.Compose(compBatch); // Initialize our ProjectTypes information from the catalog. // First, get a mapping from extension type to all available IProjectProcessor's for // that extension var processorsMap = container .GetExports <IProjectProcessor, IProjectProcessorMetadata>() .GroupBy(x => x.Metadata.ProjectExtension) .ToDictionary( x => x.Key, x => x.Select(lazy => lazy.Value).ToArray(), StringComparer.OrdinalIgnoreCase ); // Then create the ProjectTypes ProjectTypes = container .GetExports <ProjectTypeDefinition, IProjectTypeDefinitionMetadata>() .Select(lazyVal => { var md = lazyVal.Metadata; IProjectProcessor[] processors; processorsMap.TryGetValue(md.ProjectExtension, out processors); return(new ProjectType( md.CodeExtension, md.ProjectExtension, Guid.Parse(md.ProjectTypeGuid), md.SampleCode, processors )); }); // something's broken if we don't have any languages to test against, so fail the test. Assert.IsTrue(ProjectTypes.Count() > 0, "no project types were registered and no tests will run"); }
/// <exception cref="ImportCardinalityMismatchException"> /// There are zero exported objects with the contract name derived from /// <paramref name="T" /> in the <see cref="CompositionContainer" /> /// .-or-There is more than one exported object with the contract name /// derived from <paramref name="T" /> in the /// <see cref="CompositionContainer" /> . /// </exception> /// <exception cref="CompositionContractMismatchException"> /// The underlying exported object cannot be cast to /// <paramref name="T" /> . /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. /// <see cref="System.ComponentModel.Composition.CompositionException.Errors" /> /// will contain a collection of errors that occurred. /// </exception> protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); DispatcherUnhandledException += AppDispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException; catalog = new AggregateCatalog(); // Add the WpfApplicationFramework assembly to the catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModel).Assembly)); // Add the Waf.BookLibrary.Library.Presentation assembly to the catalog catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); // Add the Waf.BookLibrary.Library.Applications assembly to the catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShellViewModel).Assembly)); // Add the Common assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(ApplicationLogger).Assembly)); //Add Services assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(ICalendarService).Assembly)); //Add GoogleServices assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(IGoogleCalendarService).Assembly)); //Add OutlookServices assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(IOutlookCalendarService).Assembly)); //Add ExchangeWebServices assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(IExchangeWebCalendarService).Assembly)); //Add SyncEngine assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(ICalendarSyncEngine).Assembly)); //Add Analytics assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(SyncAnalyticsService).Assembly)); //Add Authentication.Google assembly to catalog catalog.Catalogs.Add(new AssemblyCatalog(typeof(IAccountAuthenticationService).Assembly)); //Composition Container container = new CompositionContainer(catalog, true); var batch = new CompositionBatch(); batch.AddExportedValue(container); container.Compose(batch); //Load settings var settings = container.GetExportedValue <ISettingsProvider>().GetSettings(); container.ComposeExportedValue(settings); //Load sync summary var syncSummary = container.GetExportedValue <ISyncSummaryProvider>().GetSyncSummary(); container.ComposeExportedValue(syncSummary); //Get Application logger _applicationLogger = container.GetExportedValue <ApplicationLogger>(); _applicationLogger.Setup(); //Initialize Application Controller controller = container.GetExportedValue <IApplicationController>(); controller.Initialize(); if (settings.AppSettings.StartMinimized) { _startMinimized = true; } controller.Run(_startMinimized); }
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()); // 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(SettingsServiceCommands), // Setting service commands 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 //StandardPrintCommands does not currently work with Direct2D //typeof(StandardPrintCommands), // standard File menu print commands typeof(PaletteService), // global palette, for drag/drop instancing typeof(MyPropertyEditor), // property grid for editing selected objects; uses tooltips to show property descriptions //typeof(GridPropertyEditor), // grid control for editing selected objects typeof(PropertyEditingCommands), // commands for PropertyEditor and GridPropertyEditor, like Reset, typeof(DomNodeRefDictionary), // Reference dictionary 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(TongScriptEditor), typeof(TongScriptEditorTypeManager), typeof(GroupingCommands), // circuit group/ungroup commands typeof(CircuitControlRegistry), // 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(ScriptNodeDefinitionManager), 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(DynamicPropertyCommands), // context commands for user-defined properties in the property editors typeof(ExpressionCommands), // 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 ); // enable use of the system clipboard StandardEditCommands.UseSystemClipboard = true; // 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, 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); // Add a customized category comparer to the object palette. var paletteService = container.GetExportedValue <PaletteService>(); paletteService.CategoryComparer = new CategoryComparer(); // 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(); }
public void ConventionCatalog_should_export_conventionpart() { // Setup conventions using the semantic model // This is NOT the API that the user will be exposed to, // there will be a DSL at the front var exportConvention = new ExportConvention { Members = t => new[] { t }, ContractType = x => typeof(IConventionPart), }; var importConvention = new ImportConvention { Members = t => new[] { ReflectionServices.GetProperty <IConventionPart>(p => p.Logger) }, ContractType = x => typeof(ILogger) }; var convention = new PartConvention(); convention.Imports.Add(importConvention); convention.Exports.Add(exportConvention); convention.Condition = t => t.GetInterfaces().Contains(typeof(IConventionPart)); var exportConvention2 = new ExportConvention { Members = t => new[] { typeof(NullLogger) }, ContractType = x => typeof(ILogger), }; var convention2 = new PartConvention(); convention2.Exports.Add(exportConvention2); convention2.Condition = t => t.GetInterfaces().Contains(typeof(ILogger)); var model = new FakePartRegistry2(convention, convention2); // Setup container ConventionCatalog conventionCatalog = new ConventionCatalog(model); var typeCatalog = new TypeCatalog(typeof(AttributedPart)); var aggregated = new AggregateCatalog(typeCatalog, conventionCatalog); var container = new CompositionContainer(aggregated); var part = new AttributedPart(); var batch = new CompositionBatch(); batch.AddPart(part); container.Compose(batch); // Assert part.Part.Count().ShouldEqual(2); part.Part[0].Logger.ShouldNotBeNull(); part.Part[1].Logger.ShouldNotBeNull(); }