public TestWorkspace(ExportProvider exportProvider, string?workspaceKind = null, bool disablePartialSolutions = true) : base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test) { this.TestHookPartialSolutionsDisabled = disablePartialSolutions; this.ExportProvider = exportProvider; this.Projects = new List <TestHostProject>(); this.Documents = new List <TestHostDocument>(); this.AdditionalDocuments = new List <TestHostDocument>(); this.AnalyzerConfigDocuments = new List <TestHostDocument>(); this.ProjectionDocuments = new List <TestHostDocument>(); this.CanApplyChangeDocument = true; _backgroundCompiler = new BackgroundCompiler(this); _backgroundParser = new BackgroundParser(this); _backgroundParser.Start(); _metadataAsSourceFileService = exportProvider.GetExportedValues <IMetadataAsSourceFileService>().FirstOrDefault(); RegisterDocumentOptionProviders(exportProvider.GetExports <IDocumentOptionsProviderFactory, OrderableMetadata>()); }
protected override object GetValue(ConfiguredProject project) { // Get the "natural" (unfiltered) export provider so that can we pull all the possible // values, not just the ones that are applicable to the current set of capabilities when // we call this. // // This so that when capabilities change over time, the resulting OrderPrecedenceImportCollection // responds to the changes and filters the list based on the new set of capabilities. // // This basically mimics importing OrderPrecedenceImportCollection directly. ExportProvider provider = project.Services.ExportProvider.GetExportedValue <ExportProvider>(); var values = new OrderPrecedenceImportCollection <T>(projectCapabilityCheckProvider: project); foreach (Lazy <T, IOrderPrecedenceMetadataView> value in provider.GetExports <T, IOrderPrecedenceMetadataView>()) { values.Add(value); } return(values); }
/// <summary> /// Resolves an collection of objects wrapped inside <see cref="Lazy{T,TMetadata}"/> /// from an <see cref="ExportProvider"/>. /// </summary> /// <param name="exportProvider">Export provider.</param> /// <param name="type">Type to be resolved.</param> /// <param name="metadataType">The metadata type.</param> /// <param name="name">Optional name.</param> /// <returns>Resolved collection of lazy instances or null, if no instance has been found.</returns> /// <remarks> /// Does not resolve instances which are provided by means of /// <see cref="FactoryExportProvider"/>. /// </remarks> public static IEnumerable <Lazy <object, object> > ResolveAllWithMetadata <TMetadata>(ExportProvider exportProvider, Type type, string name) { if (exportProvider == null) { throw new ArgumentNullException("exportProvider"); } if (type == null) { throw new ArgumentNullException("type"); } var exports = exportProvider.GetExports(type, typeof(TMetadata), name); if (exports.Count() == 0) { return(Enumerable.Empty <Lazy <object, object> >()); } var list = new List <Lazy <object, object> >(); foreach (var export in exports) { var lazyExportMetadata = export.Metadata as IDictionary <string, object>; if (lazyExportMetadata != null && lazyExportMetadata.ContainsKey(FactoryExportDefinition.IsFactoryExportMetadataName) && true.Equals(lazyExportMetadata[FactoryExportDefinition.IsFactoryExportMetadataName])) { continue; } if (export.Metadata is TMetadata) { list.Add(export); } } return(list); }
/// <summary> /// Tries to resolve. /// </summary> /// <param name="appServer">The application server.</param> /// <param name="exportProvider">The export provider.</param> /// <param name="result">The result.</param> /// <returns></returns> protected override bool TryResolve(IAppServer appServer, ExportProvider exportProvider, out TTarget result) { result = default(TTarget); var config = appServer.Config; var logger = appServer.Logger; var factories = exportProvider.GetExports <TTarget, TMetadata>(); if (Required) { if (factories == null || !factories.Any()) { logger.ErrorFormat("No factory for {0} defined.", typeof(TTarget).FullName); return(false); } } var configValue = ConfigSelector(config); var lazyFactory = Sort(factories).FirstOrDefault( f => string.IsNullOrEmpty(configValue) || MetadataNameEqual(f.Metadata, configValue)); if (lazyFactory == null) { if (Required) { logger.ErrorFormat("No available factory of {0} was not found!", typeof(TTarget).FullName); return(false); } return(true); } result = lazyFactory.Value; return(PrepareResult(lazyFactory.Value, appServer, lazyFactory.Metadata)); }
/// <summary> /// Resolves an object wrapped inside <see cref="Lazy{T}"/> from an <see cref="ExportProvider"/>. /// </summary> /// <param name="exportProvider">Export provider.</param> /// <param name="type">Type to be resolved.</param> /// <param name="name">Optional name.</param> /// <returns>Resolved instance or null, if no instance has been found.</returns> /// <remarks> /// Does not resolve instances which are provided by means of /// <see cref="FactoryExportProvider"/>. /// </remarks> public static Lazy <object> Resolve(ExportProvider exportProvider, Type type, string name) { if (exportProvider == null) { throw new ArgumentNullException("exportProvider"); } if (type == null) { throw new ArgumentNullException("type"); } var exports = exportProvider.GetExports(type, null, name); if (exports.Count() == 0) { return(null); } if (exports.Count() > 1) { throw new ImportCardinalityMismatchException(Resources.TooManyInstances); } var lazyExport = exports.First(); var lazyExportMetadata = lazyExport.Metadata as IDictionary <string, object>; if (lazyExportMetadata != null && lazyExportMetadata.ContainsKey(FactoryExportDefinition.IsFactoryExportMetadataName) && true.Equals(lazyExportMetadata[FactoryExportDefinition.IsFactoryExportMetadataName])) { return(null); } return(lazyExport); }
private IEnumerable <Lazy <IAsynchronousOperationListener, FeatureMetadata> > GetListeners(ExportProvider provider) { return(provider.GetExports <IAsynchronousOperationListener, FeatureMetadata>()); }
public TServiceInterface GetService <TServiceInterface>(string contentType, string name) { var values = ExportProvider.GetExports <TServiceInterface, OrderableContentTypeMetadata>(); return(values.Single(value => value.Metadata.Name == name && value.Metadata.ContentTypes.Contains(contentType)).Value); }
private static IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); }
/// <summary> /// Tries to resolve. /// </summary> /// <param name="appServer">The application server.</param> /// <param name="exportProvider">The export provider.</param> /// <param name="result">The result.</param> /// <returns></returns> protected override bool TryResolve(IAppServer appServer, ExportProvider exportProvider, out List <TTarget> result) { result = default(List <TTarget>); var config = appServer.Config; var logger = appServer.Logger; var factories = exportProvider.GetExports <TTarget, TMetadata>(); if (Required) { if (factories == null || !factories.Any()) { logger.ErrorFormat("No factory for {0} defined.", typeof(TTarget).FullName); return(false); } } var configValue = ConfigSelector(config); var configFactories = ("" + configValue).Split(",;|".ToArray(), StringSplitOptions.RemoveEmptyEntries); if (configFactories.Length == 0) { if (Required) { logger.ErrorFormat("No selected {0} configured.", typeof(TTarget).FullName); return(false); } return(true); } var finalFactories = new List <TTarget>(configFactories.Length); foreach (var c in configFactories) { var lazyFactory = factories.FirstOrDefault(x => MetadataNameEqual(x.Metadata, c)); if (lazyFactory == null) { logger.ErrorFormat("No desired {0} '{1}' was found", typeof(TTarget).FullName, c); return(false); } var factory = lazyFactory.Value; if (!PrepareResult(factory, appServer, lazyFactory.Metadata)) { return(false); } finalFactories.Add(factory); } if (!finalFactories.Any()) { if (Required) { logger.ErrorFormat("No available factory of {0} was not found!", typeof(TTarget).FullName); return(false); } return(true); } result = finalFactories; return(true); }
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; onCreate?.Invoke(res); var classifier = res.Classifier; if (classifier != null) { classifier.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); if (langInfo == null) { throw new NotImplementedException("Unable to get IVsLanguageInfo for " + info.Attribute.LanguageName); } 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); }
public async Task SearchAsync(IDependenciesTreeProjectSearchContext context) { // get latest snapshot ExportProvider exportProvider = context.UnconfiguredProject.Services.ExportProvider; Lazy <IAssetsFileDependenciesDataSource, IAppliesToMetadataView> dataSource = exportProvider .GetExports <IAssetsFileDependenciesDataSource, IAppliesToMetadataView>() .SingleOrDefault(export => export.Metadata.AppliesTo(context.UnconfiguredProject.Capabilities)); if (dataSource == null) { // dataSource will be null for shared projects, for example return; } IProjectDataSourceRegistry?dataSourceRegistry = context.UnconfiguredProject.Services.DataSourceRegistry; Assumes.Present(dataSourceRegistry); AssetsFileDependenciesSnapshot snapshot = (await dataSource.Value.GetLatestVersionAsync <AssetsFileDependenciesSnapshot>(dataSourceRegistry, cancellationToken: context.CancellationToken)).Value; if (!(context.UnconfiguredProject.Services.ExportProvider.GetExportedValue <IActiveConfigurationGroupService>() is IActiveConfigurationGroupService3 activeConfigurationGroupService)) { return; } IConfigurationGroup <ConfiguredProject> configuredProjects = await activeConfigurationGroupService.GetActiveLoadedConfiguredProjectGroupAsync(); foreach ((_, AssetsFileTarget target) in snapshot.DataByTarget) { ConfiguredProject?configuredProject = await FindConfiguredProjectAsync(target.TargetFrameworkMoniker); if (configuredProject == null) { continue; } IDependenciesTreeConfiguredProjectSearchContext?targetContext = await context.ForConfiguredProjectAsync(configuredProject); if (targetContext == null) { continue; } foreach ((_, AssetsFileTargetLibrary library) in target.LibraryByName) { if (context.CancellationToken.IsCancellationRequested) { // Search was cancelled return; } if (targetContext.IsMatch(library.Name)) { targetContext.SubmitResult(CreateLibraryItem(library)); } SearchAssemblies(library, library.CompileTimeAssemblies, PackageAssemblyGroupType.CompileTime); SearchAssemblies(library, library.FrameworkAssemblies, PackageAssemblyGroupType.Framework); SearchContentFiles(library); } SearchLogMessages(); continue; async Task <ConfiguredProject?> FindConfiguredProjectAsync(string tfm) { foreach (ConfiguredProject configuredProject in configuredProjects) { if (configuredProject.Services.ProjectSubscription == null) { continue; } IProjectSubscriptionUpdate subscriptionUpdate = (await configuredProject.Services.ProjectSubscription.ProjectRuleSource.GetLatestVersionAsync(configuredProject, cancellationToken: context.CancellationToken)).Value; if (subscriptionUpdate.CurrentState.TryGetValue(NuGetRestoreRule.SchemaName, out IProjectRuleSnapshot nuGetRestoreSnapshot) && nuGetRestoreSnapshot.Properties.TryGetValue(NuGetRestoreRule.NuGetTargetMonikerProperty, out string nuGetTargetMoniker) && StringComparer.OrdinalIgnoreCase.Equals(nuGetTargetMoniker, tfm)) { // Assets file 'target' string matches the configure project's NuGetTargetMoniker property value return(configuredProject); } if (subscriptionUpdate.CurrentState.TryGetValue(ConfigurationGeneralRule.SchemaName, out IProjectRuleSnapshot configurationGeneralSnapshot) && configurationGeneralSnapshot.Properties.TryGetValue(ConfigurationGeneralRule.TargetFrameworkMonikerProperty, out string targetFrameworkMoniker) && StringComparer.OrdinalIgnoreCase.Equals(targetFrameworkMoniker, tfm)) { // Assets file 'target' string matches the configure project's TargetFrameworkMoniker property value return(configuredProject); } } // No project found return(null); } void SearchAssemblies(AssetsFileTargetLibrary library, ImmutableArray <string> assemblies, PackageAssemblyGroupType groupType) { foreach (string assembly in assemblies) { if (targetContext.IsMatch(Path.GetFileName(assembly))) { targetContext.SubmitResult(new PackageAssemblyItem(target, library, assembly, groupType)); } } } void SearchContentFiles(AssetsFileTargetLibrary library) { foreach (AssetsFileTargetLibraryContentFile contentFile in library.ContentFiles) { if (targetContext.IsMatch(contentFile.Path)) { targetContext.SubmitResult(new PackageContentFileItem(target, library, contentFile, _fileIconProvider)); } } } IRelatableItem CreateLibraryItem(AssetsFileTargetLibrary library) { return(library.Type switch { AssetsFileLibraryType.Package => new PackageReferenceItem(target, library), AssetsFileLibraryType.Project => new ProjectReferenceItem(target, library), _ => throw Assumes.NotReachable() }); } void SearchLogMessages() { foreach (AssetsFileLogMessage log in target.Logs) { if (targetContext.IsMatch(log.Message)) { targetContext.SubmitResult(CreateLogItem(log)); } } DiagnosticItem?CreateLogItem(AssetsFileLogMessage log) { if (target.LibraryByName.TryGetValue(log.LibraryName, out AssetsFileTargetLibrary? library)) { return(new DiagnosticItem(target, library, log)); } return(null); } } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { return(_inner.GetExports(definition, atomicComposition).Where(e => _filter(e.Definition))); }