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

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

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

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

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

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

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

            moduleInitializer.Initialize(moduleInfo);

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

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

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

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

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

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

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

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

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

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

            Assert.IsFalse(module.Initialized);

            moduleInitializer.Initialize(moduleInfo);

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

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

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

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

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

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

			VerifyAllMocks();
		}
Пример #4
0
 public BaseDebuggerSessionTest()
 {
     var container = new CompositionContainer (new DirectoryCatalog (Environment.CurrentDirectory));
     session = container.GetExportedValue<IDebuggerSession> ();
     typeProvider = session.TypeProvider;
     typeProvider.AddFilter (Path.GetDirectoryName (typeof (type1).Assembly.Location));
     vm = session.VM as VirtualMachine;
 }
		public void MetadataIsOptional()
		{
			var container = new CompositionContainer(GetType().Assembly);

			var service = container.GetExportedValue<ServiceWithLazyImport>();
			Assert.IsNotNull(service.Import);
			Assert.IsNotNull(service.Import.Value);
			Assert.AreSame(service.Import.Value, service.Import.Value);
		}
		public void OnlyServicesWithMatchingMetadataAreProvided()
		{
			var container = new CompositionContainer(GetType().Assembly);

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

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

			CollectionAssert.AreEquivalent(expected, actual.ToArray());
		}
Пример #7
0
        public void Initialize(CompositionContainer composition)
        {
            sourcesWindow = composition.GetExportedValue<SourcesWindow> ();
            sourceWindow = composition.GetExportedValue<SourceWindow> ();
            windowManager.Add (sourcesWindow);
            windowManager.Add (sourceWindow);
            log = composition.GetExportedValue<LogWindow> ();
            //			windowManager.Add (log);
            windowManager.Add (composition.GetExportedValue<CallstackWindow> ());
            windowManager.Add (composition.GetExportedValue<LocalsWindow> ());
            windowManager.Add (composition.GetExportedValue<BreakpointsWindow> ());
            windowManager.Add (composition.GetExportedValue<ExecutionWindow> ());

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

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

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

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

            AdjustLayout ();

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

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

            sourcesWindow.StartRefreshing ();

            session.Start ();
        }
Пример #8
0
 public static void Start()
 {
     var compositionContainer = new CompositionContainer (new DirectoryCatalog (AssemblyPath));
     view = compositionContainer.GetExportedValue<MainWindow> ();
     view.Initialize (compositionContainer);
 }
 public override T GetService <T>(Type type = null)
 => base.GetService <T>(type) ?? _compositionContainer.GetExportedValue <T>();
Пример #10
0
 /// <summary>
 /// Initializes global static references to MEF components</summary>
 /// <param name="container">Initialized MEF composition container</param>
 public static void InitializeComponents(CompositionContainer container)
 {
     ResourceService = container.GetExportedValue <IResourceService>();
     MEFContainer    = container;
 }
Пример #11
0
 public T GetExportedValue <T>()
 {
     return(container.GetExportedValue <T>());
 }
Пример #12
0
 public static T GetService <T>()
 {
     return(container.GetExportedValue <T>());
 }
Пример #13
0
 public T GetExportedValue <T>() => _compositionContainer.GetExportedValue <T>();
Пример #14
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();
        }
 public override TabItemViewModelBase CreateTabItem()
 {
     return(_container.GetExportedValue <ThreadsViewModel>());
 }
        /// <summary>
        /// Calls initialize on all <see cref="IModule"/>s in the container/>
        /// </summary>
        /// <param name="container">The <see cref="CompositionContainer"/></param>
        private void InitializeModules(CompositionContainer container)
        {
            var moduleInitializer = container.GetExportedValue <IModuleInitializer>();

            moduleInitializer.Initialize();
        }
Пример #17
0
        static void Main(string[] args)
        {
            //MessageBox.Show(@"Get ready to debug FB exe.");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

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

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

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

            SetUpErrorHandling();

            var commandLineArgs = CommandLineProcessor.ParseCommandLineArgs(args);

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

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

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

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

                    var l10Managers = Utilities.SetupLocalization(commandLineArgs);

                    try
                    {
                        var handlerRepository = container.GetExportedValue <ActionTypeHandlerRepository>();
                        var currentHandler    = handlerRepository.GetHandler(commandLineArgs);
                        currentHandler.StartWorking(commandLineArgs);
                        var bridgeActionTypeHandlerShowWindow = currentHandler as IBridgeActionTypeHandlerShowWindow;
                        if (bridgeActionTypeHandlerShowWindow != null)
                        {
                            Application.Run(bridgeActionTypeHandlerShowWindow.MainForm);
                        }
                        var bridgeActionTypeHandlerCallEndWork = currentHandler as IBridgeActionTypeHandlerCallEndWork;
                        if (bridgeActionTypeHandlerCallEndWork != null)
                        {
                            bridgeActionTypeHandlerCallEndWork.EndWork();
                        }
                    }
                    catch
                    {
                        connHelper.SignalBridgeWorkComplete(false);
                        throw;                         // Re-throw the original exception, so the crash dlg has something to display.
                    }
                    finally
                    {
                        foreach (var manager in l10Managers.Values)
                        {
                            manager.Dispose();
                        }
                    }
                }
            }
            Settings.Default.Save();
        }
Пример #18
0
 private static IInputEventSource CreateSource <T>(CompositionContainer container) where T : IInputEventSource
 {
     Logger.DebugFormat("Using {0}", typeof(T).Name);
     return(container.GetExportedValue <T>());
 }
 public override TabItemViewModelBase CreateTabItem() => _container.GetExportedValue <ProcessesViewModel>();
Пример #20
0
        private void UIThreadWorker(object evt)
        {
            Console.WriteLine($"Started UIThreadWorker on {Thread.CurrentThread.ManagedThreadId}");
            try {
                try {
                    SynchronizationContext.SetSynchronizationContext(new MockSyncContext(this));

                    TextManager = new MockVsTextManager(this);
                    Container   = CreateCompositionContainer();
                    var serviceProvider = _serviceProvider = Container.GetExportedValue <MockVsServiceProvider>();
                    UIShell      = new MockVsUIShell(this);
                    _monSel      = new MockVsMonitorSelection(this);
                    _uiHierarchy = new MockVsUIHierarchyWindow(this);
                    _rdt         = new MockVsRunningDocumentTable(this);
                    _dte         = new MockDTE(this);
                    _serviceProvider.AddService(typeof(SVsTextManager), TextManager);
                    _serviceProvider.AddService(typeof(SVsActivityLog), ActivityLog);
                    _serviceProvider.AddService(typeof(SVsSettingsManager), SettingsManager);
                    _serviceProvider.AddService(typeof(SLocalRegistry), LocalRegistry);
                    _serviceProvider.AddService(typeof(SComponentModel), this);
                    _serviceProvider.AddService(typeof(IVsDebugger), Debugger);
                    _serviceProvider.AddService(typeof(SVsSolution), Solution);
                    _serviceProvider.AddService(typeof(SVsRegisterProjectTypes), Solution);
                    _serviceProvider.AddService(typeof(SVsCreateAggregateProject), Solution);
                    _serviceProvider.AddService(typeof(SVsTrackProjectDocuments), TrackDocs);
                    _serviceProvider.AddService(typeof(SVsShell), Shell);
                    _serviceProvider.AddService(typeof(SOleComponentManager), _compManager);
                    _serviceProvider.AddService(typeof(SVsProfferCommands), _proferredCommands);
                    _serviceProvider.AddService(typeof(SVsOutputWindow), _outputWindow);
                    _serviceProvider.AddService(typeof(SVsBuildManagerAccessor), _buildManager);
                    _serviceProvider.AddService(typeof(SVsUIHierWinClipboardHelper), _hierClipHelper);
                    _serviceProvider.AddService(typeof(IVsUIShell), UIShell);
                    _serviceProvider.AddService(typeof(IVsMonitorSelection), _monSel);
                    _serviceProvider.AddService(typeof(SVsQueryEditQuerySave), _queryEditSave);
                    _serviceProvider.AddService(typeof(SVsRunningDocumentTable), _rdt);
                    _serviceProvider.AddService(typeof(SVsUIShellOpenDocument), _shellOpenDoc);
                    _serviceProvider.AddService(typeof(SVsSolutionBuildManager), _slnBuildMgr);
                    _serviceProvider.AddService(typeof(EnvDTE.IVsExtensibility), _extensibility);
                    _serviceProvider.AddService(typeof(EnvDTE.DTE), _dte);

                    Shell.SetProperty((int)__VSSPROPID4.VSSPROPID_ShellInitialized, true);

                    UIShell.AddToolWindow(new Guid(ToolWindowGuids80.SolutionExplorer), new MockToolWindow(_uiHierarchy));

                    ErrorHandler.ThrowOnFailure(
                        _monSel.AdviseSelectionEvents(
                            new SelectionEvents(this),
                            out _monSelCookie
                            )
                        );

                    foreach (var package in Container.GetExportedValues <IMockPackage>())
                    {
                        _loadedPackages.Add(package);
                        package.Initialize();
                    }
                } finally {
                    ((AutoResetEvent)evt).Set();
                }
                RunMessageLoop();
            } catch (Exception ex) {
                Trace.TraceError("Captured exception on mock UI thread: {0}", ex);
                _edi = ExceptionDispatchInfo.Capture(ex);
            }
        }
Пример #21
0
 internal PrintController InitializePrintController()
 {
     printController = container.GetExportedValue <PrintController>();
     printController.Initialize();
     return(printController);
 }
Пример #22
0
        static void Main()
        {
            try {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                RegistrationBuilder builder = new RegistrationBuilder();
                builder.ForType <AlarmClockViewPresenter>().Export <AlarmClockViewPresenter>();
                builder.ForType <AlarmViewPresenter>().Export <IAlarmViewPresenter>();
                builder.ForType <ClockViewPresenter>().Export <IClockViewPresenter>();
                builder.ForTypesDerivedFrom <IAlarmClockView>().Export <IAlarmClockView>();
                builder.ForTypesDerivedFrom <IAlarmView>().Export <IAlarmView>();
                builder.ForTypesDerivedFrom <IClockView>().Export <IClockView>();
                //was the default singletons
                var initialAlarmClockTime             = DateTime.Now;
                var initialAlarmClockTimeContractName = "InitialClockTime";

                builder.ForType <InitializedAlarmClock>().SelectConstructor(ctors => ctors.First(), (p, ib) =>
                {
                    ib.AsContractName(initialAlarmClockTimeContractName);
                });
                builder.ForType <InitializedAlarmClock>().Export <IAlarmClock>();
                var             loc = Assembly.GetExecutingAssembly().Location;
                AssemblyCatalog defaultOrReplacement = null;
                DirectoryInfo   dir     = new DirectoryInfo(Path.GetDirectoryName(loc));
                var             isDebug = false;
#if DEBUG
                isDebug = true;
#endif
                defaultOrReplacement = new AssemblyCatalog(typeof(DefaultViews.DefaultClockView).Assembly, builder);
                if (!isDebug)
                {
                    foreach (var f in dir.GetFiles())
                    {
                        bool match = f.Name == "ReplacementParts.dll";
                        if (match)
                        {
                            defaultOrReplacement = new AssemblyCatalog(f.FullName, builder);
                            break;
                        }
                    }
                }


                var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                //DirectoryCatalog dirCatalog = new DirectoryCatalog(directory,builder);

                AssemblyCatalog exeCatalog = new AssemblyCatalog(typeof(DefaultAlarmClockView).Assembly, builder);


                AggregateCatalog     aggCatalog = new AggregateCatalog(exeCatalog, defaultOrReplacement);
                CompositionContainer container  = new CompositionContainer(aggCatalog);
                container.ComposeExportedValue <DateTime>(initialAlarmClockTimeContractName, initialAlarmClockTime);


                var alarmClockView = container.GetExportedValue <AlarmClockViewPresenter>().View as Form;
                Application.Run(alarmClockView);
            }catch (Exception exc)
            {
                var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var sw      = File.CreateText(dirName + Path.DirectorySeparatorChar + "Houston.txt");
                sw.WriteLine(exc.Message);
                sw.Flush();
                sw.Close();
            }
        }
Пример #23
0
        public static bool Init(ISettings settings)
        {
            if (loaded == true)
            {
                throw new Exception("Please only call this method once.");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            Core.Settings = settings;

            string pidFilePath = Path.Combine(Core.Settings.DataPath, "meshwork.pid");

            if (File.Exists(pidFilePath))
            {
                int processId = -1;
                Int32.TryParse(File.ReadAllText(pidFilePath), out processId);
                try
                {
                    Process.GetProcessById(processId);
                    Console.Error.WriteLine("Meshwork is already running (PID {0})!", processId);
                    return(false);
                }
                catch (ArgumentException)
                {
                    File.Delete(pidFilePath);
                }
            }
            File.WriteAllText(pidFilePath, Process.GetCurrentProcess().Id.ToString());

            if (settings.KeyEncrypted)
            {
                PasswordPrompt(null, EventArgs.Empty);
                if (!settings.KeyUnlocked)
                {
                    // Quit!
                    return(false);
                }
            }

            rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(settings.EncryptionParameters);
            nodeID = Common.SHA512Str(rsaProvider.ToXmlString(false));

            fileSystem = Container.GetExportedValue <IFileSystemProvider>();

            shareBuilder = Container.GetExportedValue <IShareBuilder>();
            shareBuilder.FinishedIndexing += ShareBuilder_FinishedIndexing;

            shareWatcher        = Container.GetExportedValue <IShareWatcher>();
            shareHasher         = Container.GetExportedValue <IShareHasher>();
            transportManager    = Container.GetExportedValue <ITransportManager>();
            fileTransferManager = Container.GetExportedValue <IFileTransferManager>();
            fileSearchManager   = Container.GetExportedValue <IFileSearchManager>();
            destinationManager  = Container.GetExportedValue <IDestinationManager>();

            // XXX: Use reflection to load these:
            destinationManager.RegisterSource(new TCPIPv4DestinationSource());
            destinationManager.RegisterSource(new TCPIPv6DestinationSource());

            MonoTorrent.Client.Tracker.TrackerFactory.Register("meshwork", typeof(MeshworkTracker));

            ITransportListener tcpListener = new TcpTransportListener(Core.Settings.TcpListenPort);

            transportListeners.Add(tcpListener);

            loaded = true;

            if (FinishedLoading != null)
            {
                FinishedLoading(null, EventArgs.Empty);
            }

            return(true);
        }
Пример #24
0
        private async Task RunExamples()
        {
            // This is the based address of the server which gets passed into the
            // creation method
            Uri baseAddress = new Uri("http://localhost:9000");

            // The factory can be created using MEF, the following is an example of how
            // you could do this:
            AssemblyCatalog      catalog   = new AssemblyCatalog(typeof(IEasyPeasyFactory).Assembly);
            CompositionContainer container = new CompositionContainer(catalog);

            IEasyPeasyFactory factory = container.GetExportedValue <IEasyPeasyFactory>();

            // Interceptors can be added to the factory to perform actions on the HTTP request and
            // response objects.  This example simply logs out the events to the console
            factory.AddInterceptor(new LoggingInterceptor());

            // An alternative would be the more direct way:
            // IEasyPeasyFactory factory = new EasyPeasyFactory(new DefaultMediaTypeRegistry());

            // Auto generate an implementation of the IContactService interface.
            // The implementation is configured via the interface attributes to determine each
            // methods end point, serialization formats etc.
            IContactServiceAsync contactService = factory.Create <IContactServiceAsync>(baseAddress);

            // The following are examples of using the implementation

            // 1 - fetch a list of contacts from the server and print them out
            // This method call maps to:
            // GET http://localhost:9000/api/contact
            List <Contact> contacts = await contactService.GetContactsAsync();

            foreach (var contact in contacts)
            {
                Console.WriteLine("Name: {0}, Address: {1}", contact.Name, contact.Address);
            }

            // Fetch a specific contact.  The value passed in here is used in the URL
            // GET http://localhost:9000/api/contact/Contact1
            Contact singleContact = await contactService.GetContactAsync("Contact1");

            Console.WriteLine("Fetched contact by name, Name: {0}, Address: {1}", singleContact.Name, singleContact.Address);

            singleContact.Address = "Changed Address";

            Console.WriteLine("Updating address for contact1");

            // Updates the contact on the server.  The supplied name is mapped to the URL,
            // the contact is serialized to the body as XML based on the Produces attribute
            await contactService.UpdateContactAsync(singleContact.Name, singleContact);

            // Another example of updating the address for a contact. This example
            // uses form encoded parameters to send the data:
            //
            // PUT   http://localhost:9000/api/contact/Contact3
            // BODY: address=Updated_using_form_param
            await contactService.UpdateContactAsync("Contact3", "Updated_using_form_param");

            // Show the updates worked by reloading the data and printing the updated values
            Console.WriteLine("Re-fetching contact list");
            List <Contact> fetchedContacts = await contactService.GetContactsAsync();

            foreach (Contact contact in fetchedContacts)
            {
                Console.WriteLine("Name: {0}, Address: {1}", contact.Name, contact.Address);
            }

            // Deletes a contact on the server using similar path mappings.
            // The DELETE attribute determines the verb to use:
            //
            // DELETE http://localhost:9000/api/contact/Contact1
            Console.WriteLine("Deleting contact 1");
            await contactService.DeleteContactAsync("Contact1");

            // Reload to show the contact has been deleted
            Console.WriteLine("Re-fetching contact list");
            fetchedContacts = await contactService.GetContactsAsync();

            foreach (Contact contact in fetchedContacts)
            {
                Console.WriteLine("Name: {0}, Address: {1}", contact.Name, contact.Address);
            }

            Console.WriteLine("Saved assembly to " + factory.SaveGeneratedAssembly().FullName);
        }
 public static T Get <T>()
 {
     return(_container.GetExportedValue <T>());
 }
Пример #26
0
 static Factory()
 {
     var compositionContainer = new CompositionContainer (new DirectoryCatalog (Environment.CurrentDirectory));
     compositionContainer.GetExportedValue<IFactory> ().Initialize ();
 }
Пример #27
0
 public override TabItemViewModelBase CreateTabItem()
 {
     return(Container.GetExportedValue <HandlesViewModel>());
 }
Пример #28
0
        public MockVs()
        {
            TextManager = new MockVsTextManager(this);
            Container   = CreateCompositionContainer();
            var serviceProvider = _serviceProvider = Container.GetExportedValue <MockVsServiceProvider>();

            UIShell      = new MockVsUIShell(this);
            _monSel      = new MockVsMonitorSelection(this);
            _uiHierarchy = new MockVsUIHierarchyWindow(this);
            _rdt         = new MockVsRunningDocumentTable(this);
            _dte         = new MockDTE(this);
            _serviceProvider.AddService(typeof(SVsTextManager), TextManager);
            _serviceProvider.AddService(typeof(SVsActivityLog), ActivityLog);
            _serviceProvider.AddService(typeof(SVsSettingsManager), SettingsManager);
            _serviceProvider.AddService(typeof(SLocalRegistry), LocalRegistry);
            _serviceProvider.AddService(typeof(SComponentModel), this);
            _serviceProvider.AddService(typeof(IVsDebugger), Debugger);
            _serviceProvider.AddService(typeof(SVsSolution), Solution);
            _serviceProvider.AddService(typeof(SVsRegisterProjectTypes), Solution);
            _serviceProvider.AddService(typeof(SVsCreateAggregateProject), Solution);
            _serviceProvider.AddService(typeof(SVsTrackProjectDocuments), TrackDocs);
            _serviceProvider.AddService(typeof(SVsShell), Shell);
            _serviceProvider.AddService(typeof(SOleComponentManager), _compManager);
            _serviceProvider.AddService(typeof(SVsProfferCommands), _proferredCommands);
            _serviceProvider.AddService(typeof(SVsOutputWindow), _outputWindow);
            _serviceProvider.AddService(typeof(SVsBuildManagerAccessor), _buildManager);
            _serviceProvider.AddService(typeof(SVsUIHierWinClipboardHelper), _hierClipHelper);
            _serviceProvider.AddService(typeof(IVsUIShell), UIShell);
            _serviceProvider.AddService(typeof(IVsMonitorSelection), _monSel);
            _serviceProvider.AddService(typeof(SVsQueryEditQuerySave), _queryEditSave);
            _serviceProvider.AddService(typeof(SVsRunningDocumentTable), _rdt);
            _serviceProvider.AddService(typeof(SVsUIShellOpenDocument), _shellOpenDoc);
            _serviceProvider.AddService(typeof(SVsSolutionBuildManager), _slnBuildMgr);
            _serviceProvider.AddService(typeof(EnvDTE.IVsExtensibility), _extensibility);
            _serviceProvider.AddService(typeof(EnvDTE.DTE), _dte);

            Shell.SetProperty((int)__VSSPROPID4.VSSPROPID_ShellInitialized, true);

            UIShell.AddToolWindow(new Guid(ToolWindowGuids80.SolutionExplorer), new MockToolWindow(_uiHierarchy));

            ErrorHandler.ThrowOnFailure(
                _monSel.AdviseSelectionEvents(
                    new SelectionEvents(this),
                    out _monSelCookie
                    )
                );

#if DEV15_OR_LATER
            // If we are not in Visual Studio, we need to set MSBUILD_EXE_PATH
            // to use any project support.
            if (!"devenv".Equals(Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), StringComparison.OrdinalIgnoreCase))
            {
                var vsPath = Environment.GetEnvironmentVariable("VisualStudio_" + AssemblyVersionInfo.VSVersion);
                if (!Directory.Exists(vsPath))
                {
                    vsPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                    if (string.IsNullOrEmpty(vsPath))
                    {
                        vsPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                    }
                    vsPath = Path.Combine(vsPath, "Microsoft Visual Studio", AssemblyVersionInfo.VSVersionSuffix);
                }
                if (Directory.Exists(vsPath))
                {
                    var msbuildPath = Path.Combine(vsPath, "MSBuild");
                    var msbuildExe  = FileUtils.EnumerateFiles(msbuildPath, "msbuild.exe").OrderByDescending(k => k).FirstOrDefault();
                    if (File.Exists(msbuildExe))
                    {
                        // Set the variable. If we haven't set it, most tests
                        // should still work, but ones trying to load MSBuild's
                        // assemblies will fail.
                        Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", msbuildExe);
                    }
                }
            }
#endif

            _throwExceptionsOn = Thread.CurrentThread;

            using (var e = new AutoResetEvent(false)) {
                UIThread      = new Thread(UIThreadWorker);
                UIThread.Name = "Mock UI Thread";
                UIThread.Start((object)e);
                // Wait for UI thread to start before returning. This ensures that
                // any packages we have are loaded and have published their services
                e.WaitOne();
            }
            ThrowPendingException();
        }
Пример #29
0
 public ILogService GetLogService()
 {
     return(container.GetExportedValue <ILogService>());
 }
Пример #30
0
 internal TestDiscoverer(CompositionContainer container)
 {
     _container          = container;
     _interpreters       = container.GetExportedValue <IInterpreterRegistryService>();
     _interpreterService = container.GetExportedValue <IInterpreterOptionsService>();
 }
Пример #31
0
        void Inner()
        {
            using (var container = new CompositionContainer(assemblyCatalog))
            {
                container.ComposeExportedValue(this);
                container.ComposeExportedValue(BuildEngine);
                container.ComposeExportedValue(logger);
                if (BuildEnginePropertyExtractor != null)
                {
                    container.ComposeExportedValue(BuildEnginePropertyExtractor);
                }
                //TODO: container.GetExportedValue<BuildEngineExtensions>().Execute();
                container.GetExportedValue <TargetPathFinder>().Execute();

                logger.LogMessage(string.Format(@"	TargetPath: {0}
	TryToWeaveAllTypes: {1}
	CheckForEquality: {2}
	EventInvokerName: {3}
	CheckForIsChanged: {4}
	ProcessFields: {5}"    , TargetPath, TryToWeaveAllTypes, CheckForEquality, EventInvokerName, CheckForIsChanged, ProcessFields));


                container.GetExportedValue <EventInvokerNameResolver>().Execute();
                container.GetExportedValue <AssemblyResolver>().Execute();
                container.GetExportedValue <ModuleReader>().Execute();
                var fileChangedChecker = container.GetExportedValue <FileChangedChecker>();
                if (!fileChangedChecker.ShouldStart())
                {
                    return;
                }
                container.GetExportedValue <MsCoreReferenceFinder>().Execute();
                container.GetExportedValue <InterceptorFinder>().Execute();
                container.GetExportedValue <TypeNodeBuilder>().Execute();
                container.GetExportedValue <DoNotNotifyTypeCleaner>().Execute();
                container.GetExportedValue <CodeGenTypeCleaner>().Execute();
                container.GetExportedValue <MethodFinder>().Execute();
                if (CheckForIsChanged)
                {
                    container.GetExportedValue <IsChangedMethodFinder>().Execute();
                }
                container.GetExportedValue <AllPropertiesFinder>().Execute();
                if (ProcessFields)
                {
                    container.GetExportedValue <FieldToPropertyConverter>().Execute();
                    container.GetExportedValue <FieldToPropertyForwarder>().Execute();
                }
                container.GetExportedValue <MappingFinder>().Execute();
                container.GetExportedValue <IlGeneratedByDependencyProcessor>().Execute();
                container.GetExportedValue <DependsOnDataAttributeReader>().Execute();
                if (!TryToWeaveAllTypes)
                {
                    container.GetExportedValue <ShouldNotifyForAllWalker>().Execute();
                }
                container.GetExportedValue <PropertyDataWalker>().Execute();
                container.GetExportedValue <ErrorChecker>().Execute();
                container.GetExportedValue <WarningChecker>().Execute();
                container.GetExportedValue <OnChangedWalker>().Execute();
                container.GetExportedValue <StackOverflowChecker>().Execute();
                container.GetExportedValue <TypeProcessor>().Execute();
                container.GetExportedValue <AttributeCleaner>().Execute();
                container.GetExportedValue <ReferenceCleaner>().Execute();
                container.GetExportedValue <ProjectKeyReader>().Execute();
                container.GetExportedValue <ModuleWriter>().Execute();
            }
        }
Пример #32
0
 public T GetInstance <T>()
 {
     return(_container.GetExportedValue <T>());
 }
 /// <summary>
 /// Resolves an instance of the type
 /// </summary>
 /// <typeparam name="T">Type to resolve</typeparam>
 /// <returns>Returns an instance of the type</returns>
 public static T Resolve <T>()
 {
     return(Container.GetExportedValue <T>());
 }
Пример #34
0
        private MockVsTextView CreateTextViewWorker(
            string contentType,
            string content,
            Action <MockVsTextView> onCreate,
            string file = null
            )
        {
            var buffer = new MockTextBuffer(content, ContentTypeRegistry.GetContentType(contentType), file);

            var view = new MockTextView(buffer);
            var res  = new MockVsTextView(_serviceProvider, this, view);

            view.Properties[typeof(MockVsTextView)] = res;
            if (onCreate != null)
            {
                onCreate(res);
            }

            foreach (var classifier in Container.GetExports <IClassifierProvider, IContentTypeMetadata>())
            {
                foreach (var targetContentType in classifier.Metadata.ContentTypes)
                {
                    if (buffer.ContentType.IsOfType(targetContentType))
                    {
                        classifier.Value.GetClassifier(buffer).GetClassificationSpans(
                            new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length)
                            );
                    }
                }
            }

            // Initialize code window
            LanguageServiceInfo info;

            if (CachedInfo.LangServicesByName.TryGetValue(contentType, out info))
            {
                var id = info.Attribute.LanguageServiceSid;
                var serviceProvider = Container.GetExportedValue <MockVsServiceProvider>();
                var langInfo        = (IVsLanguageInfo)serviceProvider.GetService(id);
                IVsCodeWindowManager mgr;
                var codeWindow = new MockCodeWindow(serviceProvider, view);
                view.Properties[typeof(MockCodeWindow)] = codeWindow;
                if (ErrorHandler.Succeeded(langInfo.GetCodeWindowManager(codeWindow, out mgr)))
                {
                    if (ErrorHandler.Failed(mgr.AddAdornments()))
                    {
                        Console.WriteLine("Failed to add adornments to text view");
                    }
                }
            }

            // Initialize intellisense imports
            var providers = Container.GetExports <IIntellisenseControllerProvider, IContentTypeMetadata>();

            foreach (var provider in providers)
            {
                foreach (var targetContentType in provider.Metadata.ContentTypes)
                {
                    if (buffer.ContentType.IsOfType(targetContentType))
                    {
                        provider.Value.TryCreateIntellisenseController(
                            view,
                            new[] { buffer }
                            );
                        break;
                    }
                }
            }

            // tell the world we have a new view...
            foreach (var listener in Container.GetExports <IVsTextViewCreationListener, IContentTypeMetadata>())
            {
                foreach (var targetContentType in listener.Metadata.ContentTypes)
                {
                    if (buffer.ContentType.IsOfType(targetContentType))
                    {
                        listener.Value.VsTextViewCreated(res);
                    }
                }
            }

            OnDispose(() => res.Close());
            return(res);
        }
Пример #35
0
 public static T GetInstance <T>()
 {
     EnsureInitialized();
     return(UIDispatcher.Execute <T>(() => _container.GetExportedValue <T>()));
 }
Пример #36
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),
                typeof(LevelEditorCore.MayaStyleCameraController),
                typeof(LevelEditorCore.ArcBallCameraController),
                typeof(LevelEditorCore.WalkCameraController),
                typeof(LevelEditorCore.FlyCameraController)
                );

            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();
        }
Пример #37
0
        public void DiscoverTests(IEnumerable <string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, "sources");
            ValidateArg.NotNull(discoverySink, "discoverySink");

            var buildEngine = new MSBuild.ProjectCollection();

            try {
                var testExecutorContext = _container.GetExportedValue <TestExecutorProjectContext>();
                // Load all the test containers passed in (.pyproj msbuild files)
                foreach (string source in sources)
                {
                    testExecutorContext.AddContext(buildEngine.LoadProject(source));
                }

                foreach (var proj in buildEngine.LoadedProjects)
                {
                    var defaultInterpreter = proj.GetPropertyValue(MSBuildConstants.InterpreterIdProperty);
                    if (String.IsNullOrWhiteSpace(defaultInterpreter))
                    {
                        defaultInterpreter = _interpreterService.DefaultInterpreterId;
                    }
                    var factory = _interpreters.FindInterpreter(defaultInterpreter);
                    if (factory == null)
                    {
                        if (!_interpreters.Configurations.Any())
                        {
                            logger.SendMessage(TestMessageLevel.Warning, "No interpreters available for project " + proj.FullPath);
                        }
                        continue;
                    }

                    var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, proj.GetPropertyValue(PythonConstants.ProjectHomeSetting) ?? "."));

                    // Do the analysis even if the database is not up to date. At
                    // worst, we'll get no results.
                    using (var analyzer = new TestAnalyzer(
                               factory,
                               proj.FullPath,
                               projectHome,
                               TestExecutor.ExecutorUri
                               )) {
                        // Provide all files to the test analyzer
                        foreach (var item in proj.GetItems("Compile"))
                        {
                            string fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                            string fullName;

                            try {
                                fullName = ModulePath.FromFullPath(fileAbsolutePath).ModuleName;
                            } catch (ArgumentException) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "File has an invalid module name: " + fileAbsolutePath);
                                }
                                continue;
                            }

                            try {
                                using (var reader = new StreamReader(fileAbsolutePath)) {
                                    analyzer.AddModule(fullName, fileAbsolutePath, reader);
                                }
                            } catch (FileNotFoundException) {
                                // user deleted file, we send the test update, but the project
                                // isn't saved.
#if DEBUG
                            } catch (Exception ex) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                    logger.SendMessage(TestMessageLevel.Informational, ex.ToString());
                                }
                            }
#else
                            } catch (Exception) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                }
                            }
#endif
                        }
Пример #38
0
        public T GetInstance <T>()
        {
            var contract = AttributedModelServices.GetContractName(typeof(T));

            return(m_Container.GetExportedValue <T>(contract));
        }
Пример #39
0
 public static void Start()
 {
     Console.WriteLine("Start: " + AssemblyPath);
     var compositionContainer = new CompositionContainer(new DirectoryCatalog(AssemblyPath));
     view = compositionContainer.GetExportedValue<MainWindow>();
 }
Пример #40
0
 internal VimComponentHost()
 {
     _vim = CompositionContainer.GetExportedValue <IVim>();
 }