Exemple #1
0
 public DocumentBuilder(
     IEnumerable<Assembly> assemblies,
     ImmutableArray<string> postProcessorNames,
     string templateHash,
     string intermediateFolder = null,
     string commitFromSHA = null,
     string commitToSHA = null)
 {
     Logger.LogVerbose("Loading plug-in...");
     using (new LoggerPhaseScope("ImportPlugins", true))
     {
         var assemblyList = assemblies?.ToList();
         _container = GetContainer(assemblyList);
         _container.SatisfyImports(this);
         _currentBuildInfo.CommitFromSHA = commitFromSHA;
         _currentBuildInfo.CommitToSHA = commitToSHA;
         if (intermediateFolder != null)
         {
             _currentBuildInfo.PluginHash = ComputePluginHash(assemblyList);
             _currentBuildInfo.TemplateHash = templateHash;
             _currentBuildInfo.DirectoryName = IncrementalUtility.CreateRandomDirectory(intermediateFolder);
         }
     }
     Logger.LogInfo($"{Processors.Count()} plug-in(s) loaded.");
     foreach (var processor in Processors)
     {
         Logger.LogVerbose($"\t{processor.Name} with build steps ({string.Join(", ", from bs in processor.BuildSteps orderby bs.BuildOrder select bs.Name)})");
     }
     _postProcessors = GetPostProcessor(postProcessorNames);
     _intermediateFolder = intermediateFolder;
     _lastBuildInfo = LoadLastBuildInfo();
 }
Exemple #2
0
        public DfmEngineBuilder(Options options, CompositionHost host = null) : base(options)
        {
            var inlineRules = InlineRules.ToList();

            var index = inlineRules.FindLastIndex(s => s is MarkdownLinkInlineRule);
            if (index < 0) throw new ArgumentException("MarkdownLinkInlineRule should exist!");
            inlineRules.Insert(index + 1, new DfmXrefInlineRule());
            inlineRules.Insert(index + 1, new DfmEmailInlineRule());
            inlineRules.Insert(index, new DfmIncludeInlineRule());
            index = inlineRules.FindIndex(s => s is MarkdownTextInlineRule);
            inlineRules[index] = new DfmTextInlineRule();

            var blockRules = BlockRules.ToList();
            index = blockRules.FindLastIndex(s => s is MarkdownNewLineBlockRule);
            if (index < 0) throw new ArgumentException("MarkdownNewLineBlockRule should exist!");
            blockRules.Insert(index + 1, new DfmIncludeBlockRule());
            blockRules.Insert(index + 2, new DfmYamlHeaderBlockRule());
            blockRules.Insert(index + 3, new DfmSectionBlockRule());
            blockRules.Insert(index + 4, new DfmFencesBlockRule());
            blockRules.Insert(index + 5, new DfmNoteBlockRule());

            var gfmIndex = blockRules.FindIndex(item => item is GfmParagraphBlockRule);
            blockRules[gfmIndex] = new DfmParagraphBlockRule();

            var markdownBlockQuoteIndex = blockRules.FindIndex(item => item is MarkdownBlockquoteBlockRule);
            blockRules[markdownBlockQuoteIndex] = new DfmBlockquoteBlockRule();

            InlineRules = inlineRules.ToImmutableList();
            BlockRules = blockRules.ToImmutableList();

            Rewriter = InitMarkdownStyleCop(host);
        }
 /// <summary>
 /// Injects the container. Use this for unit testing where you want to control the type reasolving.
 /// </summary>
 /// <param name="container">The container.</param>
 public static void InjectContainer(CompositionHost container)
 {
   lock (_syncRoot)
   {
     _container = container;
   }
 }
        public MefDependencyResolver(AttributedModelProvider builder, IDependencyResolver resolver)
        {
            _container = new ContainerConfiguration()
                .WithAssemblies(AppDomain.CurrentDomain.GetAssemblies(), builder)
                .CreateContainer();

            _resolver = resolver;
        }
Exemple #5
0
        protected void Compose()
        {
            // Create the container
            var config = new ContainerConfiguration();
            ConfigureContainer(config);
            _container = config.CreateContainer();

            // Compose the application
            _container.SatisfyImports(this);
        }
        public override void Dispose()
        {
            // Allow the container and everything it references to be garbage collected.
            if (this.container == null)
            {
                return;
            }

            this.container.Dispose();
            this.container = null;
        }
Exemple #7
0
        protected override void OnInitialize()
        {
            base.OnInitialize();

            Context = UnitTestSynchronizationContext.Create();

            var configuration = new ContainerConfiguration()
                .WithAssembly(typeof(ShellViewModel).GetTypeInfo().Assembly)
                .WithAssembly(typeof(ApplicationsTest).GetTypeInfo().Assembly);
            Container = configuration.CreateContainer();
        }
        public MefDependencyResolver(CompositionHost rootCompositionScope) : base(new Export<CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose)) {

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

            var factoryContract = new CompositionContract(typeof(ExportFactory<CompositionContext>), null, new Dictionary<string, object> {
                { "SharingBoundaryNames", new[] { "HttpRequest" } }
            });

            this.RequestScopeFactory = (ExportFactory<CompositionContext>)rootCompositionScope.GetExport(factoryContract);
        }
        public EndpointMiddleware(RequestDelegate next, CompositionHost host, ILoggerFactory loggerFactory)
        {
            _next = next;
            _host = host;
            _projectSystems = host.GetExports<IProjectSystem>();
            _logger = loggerFactory.CreateLogger<EndpointMiddleware>();
            var endpoints = _host.GetExports<Lazy<IRequest, EndpointDescriptor>>()
                .Select(x => x.Metadata);

            var handlers = _host.GetExports<Lazy<IRequestHandler, OmniSharpLanguage>>();

            _endpoints = new HashSet<string>(
                    endpoints
                        .Select(x => x.EndpointName)
                        .Distinct(),
                    StringComparer.OrdinalIgnoreCase
                );

            var updateBufferEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>(() => (EndpointHandler<UpdateBufferRequest, object>)_endpointHandlers[OmnisharpEndpoints.UpdateBuffer].Value);
            var languagePredicateHandler = new LanguagePredicateHandler(_projectSystems);
            var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects");
            var nugetPredicateHandler = new StaticLanguagePredicateHandler("NuGet");
            var endpointHandlers = endpoints.ToDictionary(
                    x => x.EndpointName,
                    endpoint => new Lazy<EndpointHandler>(() =>
                    {
                        IPredicateHandler handler;

                        // Projects are a special case, this allows us to select the correct "Projects" language for them
                        if (endpoint.EndpointName == OmnisharpEndpoints.ProjectInformation || endpoint.EndpointName == OmnisharpEndpoints.WorkspaceInformation)
                            handler = projectSystemPredicateHandler;
                        else if (endpoint.EndpointName == OmnisharpEndpoints.PackageSearch || endpoint.EndpointName == OmnisharpEndpoints.PackageSource || endpoint.EndpointName == OmnisharpEndpoints.PackageVersion)
                            handler = nugetPredicateHandler;
                        else
                            handler = languagePredicateHandler;

                        // This lets any endpoint, that contains a Request object, invoke update buffer.
                        // The language will be same language as the caller, this means any language service
                        // must implement update buffer.
                        var updateEndpointHandler = updateBufferEndpointHandler;
                        if (endpoint.EndpointName == OmnisharpEndpoints.UpdateBuffer)
                        {
                            // We don't want to call update buffer on update buffer.
                            updateEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>(() => null);
                        }

                        return EndpointHandler.Factory(handler, _host, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty<Plugin>());
                    }),
                    StringComparer.OrdinalIgnoreCase
                );

            _endpointHandlers = new ReadOnlyDictionary<string, Lazy<EndpointHandler>>(endpointHandlers);
        }
        public override void Prepare()
        {
            var config = new ContainerConfiguration();

            RegisterBasic(config);
            
            RegisterPropertyInjection(config);
            RegisterMultiple(config);
            RegisterOpenGeneric(config);

            this.container = config.CreateContainer();
        }
        public override void Prepare()
        {
            var config = new ContainerConfiguration();

            RegisterDummies(config);
            RegisterStandard(config);
            RegisterComplexObject(config);
            RegisterPropertyInjection(config);
            RegisterMultiple(config);
            RegisterOpenGeneric(config);

            this.container = config.CreateContainer();
        }
        /// <summary>
        /// Create the container. The value returned from this method provides
        /// the exports in the container, as well as a means to dispose the container.
        /// </summary>
        /// <returns>The container.</returns>
        public CompositionHost CreateContainer()
        {
            var providers = _addedSources.ToList();

            foreach (var typeSet in _types)
            {
                var ac = typeSet.Item2 ?? _defaultAttributeContext ?? new DirectAttributeContext();

                providers.Add(new TypedPartExportDescriptorProvider(typeSet.Item1, ac));
            }

            return(CompositionHost.CreateCompositionHost(providers.ToArray()));
        }
Exemple #13
0
        private void EnsureContainer()
        {
            if (_container != null)
            {
                return;
            }
#if COREFX
            var configuration = new ContainerConfiguration().WithAssembly(typeof(ElementDifferenceFactory).GetTypeInfo().Assembly);
            _container = configuration.CreateContainer();
#else
            _container = new CompositionContainer(new AssemblyCatalog(typeof(ElementDifferenceFactory).Assembly));
#endif
        }
        private OmnisharpWorkspace CreateWorkspace(
            CompositionHost compositionHost,
            Dictionary<string, string> sourceFiles)
        {
            compositionHost = compositionHost ?? CreatePluginHost(typeof(CodeCheckService).GetTypeInfo().Assembly);

            var workspace = compositionHost.GetExport<OmnisharpWorkspace>();
            AddProjectToWorkspace(workspace, "project.json", new[] { "dnx451", "dnxcore50" }, sourceFiles);

            // Logic is copied from TestHelper, no idea what's waiting for.
            Thread.Sleep(50);

            return workspace;
        }
        public StandaloneDependencyResolver(CompositionHost rootCompositionScope)
            : base(new Export<CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose))
        {
            if (rootCompositionScope == null)
            {
                throw new ArgumentNullException(nameof(rootCompositionScope));
            }

            var metadataConstraints = new Dictionary<string, object>
            {
                { "SharingBoundaryNames", new[] { "HttpRequest" } }
            };

            var factoryContract = new CompositionContract(typeof(ExportFactory<CompositionContext>), contractName: null, metadataConstraints: metadataConstraints);

            this.requestScopeFactory = (ExportFactory<CompositionContext>)rootCompositionScope.GetExport(factoryContract);
        }
Exemple #16
0
 private static IMarkdownTokenRewriter InitMarkdownStyleCop(CompositionHost host)
 {
     try
     {
         if (File.Exists(MarkdownStyleCopFileName))
         {
             var rules = JsonUtility.Deserialize<MarkdownTagValidationRule[]>(MarkdownStyleCopFileName);
             var builder = new MarkdownRewriterBuilder(host);
             builder.AddValidators(rules);
             return builder.Create();
         }
     }
     catch (Exception ex)
     {
         Logger.LogWarning($"Fail to init markdown stylecop, details:{Environment.NewLine}{ex.ToString()}");
     }
     return null;
 }
Exemple #17
0
 private static IMarkdownTokenRewriter InitMarkdownStyle(CompositionHost host)
 {
     try
     {
         if (File.Exists(MarkdownSytleConfig.MarkdownStyleFileName))
         {
             var config = JsonUtility.Deserialize<MarkdownSytleConfig>(MarkdownSytleConfig.MarkdownStyleFileName);
             var builder = new MarkdownValidatorBuilder(host);
             builder.AddValidators(from r in config.Rules where !r.Disable select r.RuleName);
             builder.AddTagValidators(config.TagRules);
             return builder.Create();
         }
     }
     catch (Exception ex)
     {
         Logger.LogWarning($"Fail to init markdown style, details:{Environment.NewLine}{ex.ToString()}");
     }
     return null;
 }
 public static Task<OmnisharpWorkspace> CreateSimpleWorkspace(CompositionHost host, string source, string fileName = "dummy.cs")
 {
     return CreateSimpleWorkspace(host, new Dictionary<string, string> { { fileName, source } });
 }
        public static void Initialize(IEnumerable<Assembly> assemblies)
        {
            if (assemblies == null)
                throw new ArgumentNullException(nameof(assemblies));
            if (host != null)
                throw new InvalidOperationException(Resources.CompositionHostAlreadyInitialized);

            host = InitializeHost(assemblies);
            OnHostInitialized();
        }
        public static void Initialize(string path, string searchPattern)
        {
            if (path == null)
                throw new ArgumentNullException(nameof(path));

            var assemblies = new List<Assembly>();

            var directory = new DirectoryInfo(path);
            if (directory.Exists)
                foreach (var file in directory.EnumerateFiles(searchPattern))
                    assemblies.Add(Assembly.LoadFrom(file.FullName));

            host = InitializeHost(assemblies);
            OnHostInitialized();
        }
 public ApplicationInitializedMessage(Frame rootFrame, CompositionHost container)
 {
     RootFrame = rootFrame;
     Container = container;
 }
Exemple #22
0
 public ElementDifferenceFactory(CompositionContainer container, Func <IDifferenceRuleMetadata, bool> ruleFilter = null)
 {
     Contract.Requires(container != null);
     _container  = container;
     _ruleFilter = ruleFilter;
 }
 public MarkdownRewriterBuilder(CompositionHost host)
 {
     CompositionHost = host;
     Validators = ImmutableList<MarkdownTagValidationRule>.Empty;
 }
Exemple #24
0
 private static IMarkdownTokenRewriter InitMarkdownStyle(CompositionHost host, string baseDir, string templateDir)
 {
     try
     {
         return MarkdownValidatorBuilder.Create(host, baseDir, templateDir).CreateRewriter();
     }
     catch (Exception ex)
     {
         Logger.LogWarning($"Fail to init markdown style, details:{Environment.NewLine}{ex.ToString()}");
     }
     return null;
 }
 private async Task<RunCodeActionResponse> RunRefactoringsAsync(string source, string identifier, bool wantsChanges = false)
 {
     var request = CreateRunCodeActionRequest(source, identifier, wantsChanges);
     _host = _host ?? TestHelpers.CreatePluginHost(new[] { typeof(RoslynCodeActionProvider).GetTypeInfo().Assembly, typeof(NRefactoryCodeActionProvider).GetTypeInfo().Assembly, typeof(GetCodeActionsService).GetTypeInfo().Assembly });
     _workspace = _workspace ?? await TestHelpers.CreateSimpleWorkspace(_host, request.Buffer, bufferPath);
     var controller = new RunCodeActionService(_workspace, new ICodeActionProvider[] { new RoslynCodeActionProvider(), new NRefactoryCodeActionProvider() }, new FakeLoggerFactory());
     var response = await controller.Handle(request);
     return response;
 }
 private async Task<IEnumerable<OmniSharpCodeAction>> FindRefactoringsAsync(string source)
 {
     var request = CreateGetCodeActionsRequest(source);
     _host = _host ?? TestHelpers.CreatePluginHost(new[] { typeof(RoslynCodeActionProvider).GetTypeInfo().Assembly, typeof(NRefactoryCodeActionProvider).GetTypeInfo().Assembly, typeof(GetCodeActionsService).GetTypeInfo().Assembly });
     _workspace = _workspace ?? await TestHelpers.CreateSimpleWorkspace(_host, request.Buffer, bufferPath);
     var controller = new GetCodeActionsService(_workspace, new ICodeActionProvider[] { new RoslynCodeActionProvider(), new NRefactoryCodeActionProvider() }, new FakeLoggerFactory());
     var response = await controller.Handle(request);
     return response.CodeActions;
 }
        public async static Task<OmnisharpWorkspace> CreateSimpleWorkspace(CompositionHost _host, Dictionary<string, string> sourceFiles)
        {
            var host = _host ?? CreatePluginHost(new[] { typeof(CodeCheckService).GetTypeInfo().Assembly });

            var workspace = host.GetExport<OmnisharpWorkspace>();
            await AddProjectToWorkspace(workspace, "project.json", new[] { "dnx451", "dnxcore50" }, sourceFiles);

            await Task.Delay(50);
            return workspace;
        }
        public void Configure(IApplicationBuilder app,
                              IServiceProvider serviceProvider,
                              IOmnisharpEnvironment env,
                              ILoggerFactory loggerFactory,
                              ISharedTextWriter writer,
                              IOmnisharpAssemblyLoader loader,
                              IOptions<OmniSharpOptions> optionsAccessor)
        {
            Func<RuntimeLibrary, bool> shouldLoad = lib => lib.Dependencies.Any(dep => dep.Name == "OmniSharp.Abstractions" ||
                                                                                       dep.Name == "OmniSharp.Roslyn");
                       
            var assemblies = DependencyContext.Default
                                              .RuntimeLibraries
                                              .Where(shouldLoad)
                                              .SelectMany(lib => lib.Assemblies)
                                              .Select(each => loader.Load(each.Name))
                                              .ToList();

            PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies);

            Workspace = PluginHost.GetExport<OmnisharpWorkspace>();

            if (env.TransportType == TransportType.Stdio)
            {
                loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env));
            }
            else
            {
                loggerFactory.AddConsole((category, level) => LogFilter(category, level, env));
            }

            var logger = loggerFactory.CreateLogger<Startup>();
            foreach (var assembly in assemblies)
            {
                logger.LogDebug($"Loaded {assembly.FullName}");
            }

            app.UseRequestLogging();
            app.UseExceptionHandler("/error");
            app.UseMiddleware<EndpointMiddleware>();
            app.UseMiddleware<StatusMiddleware>();
            app.UseMiddleware<StopServerMiddleware>();

            if (env.TransportType == TransportType.Stdio)
            {
                logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{env.Path}' on host {env.HostPID}.");
            }
            else
            {
                logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}.");
            }

            // ProjectEventForwarder register event to OmnisharpWorkspace during instantiation
            PluginHost.GetExport<ProjectEventForwarder>();
            
            // Initialize all the project systems
            foreach (var projectSystem in PluginHost.GetExports<IProjectSystem>())
            {
                try
                {
                    projectSystem.Initalize(Configuration.GetSection(projectSystem.Key));
                }
                catch (Exception e)
                {
                    var message = $"The project system '{projectSystem.GetType().Name}' threw exception during initialization.\n{e.Message}\n{e.StackTrace}";
                    // if a project system throws an unhandled exception it should not crash the entire server
                    logger.LogError(message);
                }
            }

            // Mark the workspace as initialized
            Workspace.Initialized = true;

            logger.LogInformation("Configuration finished.");
        }
 public MarkdownRewriterContext(CompositionHost host, ImmutableList<MarkdownTagValidationRule> validators)
 {
     CompositionHost = host;
     Validators = validators;
 }
 public static void InitializeContainer(IEnumerable<string> appAssemblyNames)
 {
   var assemblies = appAssemblyNames.Select(p => Assembly.Load(new AssemblyName(p)));
   var configuration = new ContainerConfiguration().WithAssemblies(assemblies);
   _container = configuration.CreateContainer();
 }
 public static void InitializeContainer(IEnumerable<Assembly> appAssemblies)
 {
   var configuration = new ContainerConfiguration().WithAssemblies(appAssemblies);
   _container = configuration.CreateContainer();
 }
Exemple #32
0
 void SetupMef()
 {
     MefContainer = new ContainerConfiguration()
         .WithAssembly(typeof(Program).Assembly)
         .WithAssemblies(Directory.EnumerateFiles(AppDirectory, typeof(Program).Assembly.GetName().Name + ".*.dll")
                                  .Select(Assembly.LoadFrom))
         .CreateContainer();
 }
 public override void PrepareBasic()
 {
     var config = new ContainerConfiguration();
     RegisterBasic(config);        
     this.container = config.CreateContainer();
 }