public void Configure( IApplicationBuilder app, IHostApplicationLifetime lifetime, IBrowserLauncher browserLauncher, IDirectoryAccessor directoryAccessor, PackageRegistry packageRegistry) { using (var operation = Log.OnEnterAndConfirmOnExit()) { lifetime.ApplicationStopping.Register(() => _disposables.Dispose()); ConfigureForOrchestratorProxy(app); // Serve Blazor on the /LocalCodeRunner/blazor-console prefix app.Map("/LocalCodeRunner/blazor-console", blazor => { blazor.UseClientSideBlazorFiles <MLS.Blazor.Startup>(); blazor.UseRouting(); blazor.UseEndpoints(endpoints => { endpoints.MapFallbackToClientSideBlazor <MLS.Blazor.Startup>("index.html"); }); }); var budget = new Budget(); _disposables.Add(() => budget.Cancel()); BlazorPackageConfiguration.Configure(app, app.ApplicationServices, packageRegistry, budget, !StartupOptions.IsLanguageService); app.UseMvc() .UseDefaultFiles() .UseStaticFilesFromToolLocationAndRootDirectory(directoryAccessor.GetFullyQualifiedRoot()); operation.Succeed(); if (StartupOptions.Mode == StartupMode.Try && !StartupOptions.IsJupyter) { var uri = new Uri(app.ServerFeatures.Get <IServerAddressesFeature>().Addresses.First()); Clock.Current .Schedule(_ => LaunchBrowser(browserLauncher, directoryAccessor, uri), TimeSpan.FromSeconds(1)); } } }
public void Configure( IApplicationBuilder app, IApplicationLifetime lifetime, IBrowserLauncher browserLauncher, IDirectoryAccessor directoryAccessor, PackageRegistry packageRegistry) { using (var operation = Log.OnEnterAndConfirmOnExit()) { lifetime.ApplicationStopping.Register(() => _disposables.Dispose()); ConfigureForOrchestratorProxy(app); app.Map("/LocalCodeRunner/blazor-console", builder => { builder.UsePathBase("/LocalCodeRunner/blazor-console/"); builder.EnableCachingBlazorContent(); builder.UseBlazor <MLS.Blazor.Program>(); }); app.Map("/LocalCodeRunner/humanizer.api", builder => { builder.UsePathBase("/LocalCodeRunner/humanizer/"); builder.EnableCachingBlazorContent(); builder.UseBlazor <MLS.HumanizerRunner.Program>(); }); var budget = new Budget(); _disposables.Add(() => budget.Cancel()); BlazorPackageConfiguration.Configure(app, app.ApplicationServices, packageRegistry, budget, !StartupOptions.IsLanguageService); app.UseDefaultFiles() .UseStaticFilesFromToolLocation() .UseRouter(new StaticFilesProxyRouter()) .UseMvc(); operation.Succeed(); if (StartupOptions.Mode == StartupMode.Try) { Clock.Current .Schedule(_ => LaunchBrowser(browserLauncher, directoryAccessor), TimeSpan.FromSeconds(1)); } } }
public LocalCodeFenceAnnotationsParser( IDirectoryAccessor directoryAccessor, PackageRegistry packageRegistry, IDefaultCodeBlockAnnotations defaultAnnotations = null) : base(defaultAnnotations, csharp => { AddCsharpProjectOption(csharp, directoryAccessor); AddSourceFileOption(csharp); }, fsharp => { AddFsharpProjectOption(fsharp, directoryAccessor); AddSourceFileOption(fsharp); }) { _directoryAccessor = directoryAccessor; _packageRegistry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry)); }
public void Returns_list_of_all_relative_paths_to_all_markdown_files() { var workingDir = TestAssets.SampleConsole; var dirAccessor = new InMemoryDirectoryAccessor(workingDir) { ("Readme.md", ""), ("Subdirectory/Tutorial.md", ""), ("Program.cs", "") }; var project = new MarkdownProject(dirAccessor, PackageRegistry.CreateForHostedMode()); var files = project.GetAllMarkdownFiles(); files.Should().HaveCount(2); files.Should().Contain(f => f.Path.Value.Equals("./Readme.md")); files.Should().Contain(f => f.Path.Value.Equals("./Subdirectory/Tutorial.md")); }
public void should_NOT_run_activators() { bool hasNotRun = true; PackageRegistry.LoadPackages(x => { x.Bootstrap(log => { return(new List <IActivator>() { new LambdaActivator("x", () => { hasNotRun = false; }) }); }); }, runActivators: false); hasNotRun.ShouldBeTrue(); }
public void each_smart_grid_harness_is_registered_by_name_in_the_container() { var container = new Container(x => { x.For <IRepository>().Use <InMemoryRepository>(); x.For <IEntityFinder>().Use <EntityFinder>(); x.For <IEntityFinderCache>().Use <StructureMapEntityFinderCache>(); }); FubuApplication.For(() => theRegistry) .StructureMap(() => container) .Packages(x => x.Assembly(typeof(ISmartGrid).Assembly)) .Bootstrap(); PackageRegistry.AssertNoFailures(); container.GetInstance <ISmartGridHarness>("Fake1").ShouldBeOfType <SmartGridHarness <Fake1Grid> >(); container.GetInstance <ISmartGridHarness>("Fake2").ShouldBeOfType <SmartGridHarness <Fake2Grid> >(); }
public async Task EnableBlazor_registers_another_package() { var builder = new PackageBuilder("test"); var registry = new PackageRegistry(); builder.EnableBlazor(registry); var addedBuilder = registry.First(t => t.Result.PackageName == "runner-test").Result; addedBuilder.BlazorSupported.Should().BeTrue(); var package = await registry.Get <IHaveADirectory>("runner-test"); package.Should().NotBeNull(); package.Directory.Name.Should().Be("MLS.Blazor"); }
public void should_run_activators() { bool ran = false; PackageRegistry.LoadPackages(x => { x.Bootstrap(log => { return(new List <IActivator>() { new LambdaActivator("x", () => { ran = true; }) }); }); }); ran.ShouldBeTrue(); }
public MarkdownProcessingContext( IDirectoryAccessor rootDirectory, IDefaultCodeBlockAnnotations defaultAnnotations = null, WriteFile writeFile = null, IConsole console = null) { RootDirectory = rootDirectory; Console = console ?? new SystemConsole(); var packageRegistry = PackageRegistry.CreateForTryMode(rootDirectory); Project = new MarkdownProject( rootDirectory, packageRegistry, defaultAnnotations ?? new DefaultCodeBlockAnnotations()); _lazyWorkspaceServer = new Lazy <IWorkspaceServer>(() => new WorkspaceServerMultiplexer(packageRegistry)); WriteFile = writeFile ?? File.WriteAllText; }
private void CreateContext() { if (Program.Configuration.InstallationPath != null) { return; } AddLog(Labels.CreatingContext, Program.Configuration.Context.Name); // Ensure we have the installation folder. if (!Directory.Exists(_configuration.InstallationPath)) { Directory.CreateDirectory(_configuration.InstallationPath); } // Create the registry root. using (var key = PackageRegistry.OpenRegistryRoot(true, Program.Configuration.Context)) { key.SetValue("InstallationPath", _configuration.InstallationPath); } // Write the NiContext.xml file. var document = new XDocument( new XElement( (XNamespace)Ns.Context + "context", new XAttribute( "name", Program.Configuration.Context.Name ), new XAttribute( "nuGetSite", Program.Configuration.NuGetWebsite ) ) ); document.Save(Path.Combine(_configuration.InstallationPath, Context.FileName)); }
public IList <RouteBase> Bootstrap() { if (HttpContext.Current != null) { UrlContext.Live(); } _fubuFacility = new FubuMvcPackageFacility(); // TODO -- would be nice if this little monster also logged PackageRegistry.LoadPackages(x => { x.Facility(_fubuFacility); _packagingDirectives.Each(d => d(x)); x.Bootstrap(log => startApplication()); }); PackageRegistry.AssertNoFailures(); return(buildRoutes()); }
public JupyterRequestContextHandler( PackageRegistry packageRegistry, IKernel kernel) { var scheduler = new EventLoopScheduler(t => { var thread = new Thread(t); thread.IsBackground = true; thread.Name = "MessagePump"; return(thread); }); _executeHandler = new ExecuteRequestHandler(kernel, scheduler); _completeHandler = new CompleteRequestHandler(kernel, scheduler); if (packageRegistry == null) { throw new ArgumentNullException(nameof(packageRegistry)); } _server = new WorkspaceServerMultiplexer(packageRegistry); }
public static void Start() { // FubuApplication "guides" the bootstrapping of the FubuMVC // application FubuApplication.For <ConfigureFubuMVC>() // ConfigureFubuMVC is the main FubuRegistry // for this application. FubuRegistry classes // are used to register conventions, policies, // and various other parts of a FubuMVC application // FubuMVC requires an IoC container for its own internals. // In this case, we're using a brand new StructureMap container, // but FubuMVC just adds configuration to an IoC container so // that you can use the native registration API's for your // IoC container for the rest of your application .StructureMap(new Container()) .Bootstrap(); // Ensure that no errors occurred during bootstrapping PackageRegistry.AssertNoFailures(); }
public override bool Execute(ExplodeInput input) { var system = new FileSystem(); if (input.CleanFlag) { var contentFolder = input.Directory.AppendPath(FubuMvcPackageFacility.FubuContentFolder); Console.WriteLine("Cleaning contents of folder " + contentFolder); system.CleanDirectory(contentFolder); } FubuMvcPackageFacility.PhysicalRootPath = input.Directory.ToFullPath(); PackageRegistry.GetApplicationDirectory = FubuMvcPackageFacility.GetApplicationPath; Console.WriteLine("Exploding bottle content at " + FubuMvcPackageFacility.GetApplicationPath().ToFullPath()); PackageRegistry.LoadPackages(_ => _.Loader(new FubuModuleExploder(input.Directory))); return(true); }
protected void Application_Start() { // TODO -- add smart grid controllers FubuApplication.For <FubuTestApplicationRegistry>() .ContainerFacility(() => { var databaseFile = FileSystem.Combine(FubuMvcPackageFacility.GetApplicationPath(), @"..\..\test.db").ToFullPath(); var container = DatabaseDriver.BootstrapContainer(databaseFile, false); container.Configure( x => { x.Activate <ISchemaWriter>("Building the schema", writer => { writer.BuildSchema(); }); }); return(new TransactionalStructureMapContainerFacility(container)); }) // TODO -- convenience method here? .Packages(x => x.Assembly(typeof(IGridColumn).Assembly)) .Bootstrap(RouteTable.Routes); PackageRegistry.AssertNoFailures(); }
public void environment_checks_are_logged_in_diagnostic_log() { var activator = new FakeActivator(); activator.SucceedWith("good"); activator.SucceedWith("better"); activator.FailWith("worst"); var activator2 = new FakeActivator(); var activator3 = new FakeActivator(); PackageRegistry.LoadPackages(x => { x.Activator(activator); x.Activator(activator2); x.Activator(activator3); }); PackageRegistry.Diagnostics.LogsForSubjectType <IEnvironmentRequirement>() .Select(x => x.Subject) .ShouldHaveTheSameElementsAs(activator.Requirements()); }
public void activators_do_not_run_if_any_environment_check_fails() { var activator = new FakeActivator(); activator.SucceedWith("good"); activator.SucceedWith("better"); activator.FailWith("worst"); var activator2 = new FakeActivator(); var activator3 = new FakeActivator(); PackageRegistry.LoadPackages(x => { x.Activator(activator); x.Activator(activator2); x.Activator(activator3); }); activator.WasActivated.ShouldBeFalse(); activator2.WasActivated.ShouldBeFalse(); activator3.WasActivated.ShouldBeFalse(); }
private static async Task Packages(ArgList args) { var command = args.PopCommand()?.ToLowerInvariant(); switch (command) { case "list": await list(); break; default: Console.WriteLine("Usage:"); Console.WriteLine("romp packages list"); break; } async Task list() { using (var registry = PackageRegistry.GetRegistry(RompConfig.UserMode)) { var packages = await registry.GetInstalledPackagesAsync(); if (packages.Count > 0) { Console.WriteLine("Installed packages:"); foreach (var p in packages) { Console.WriteLine($" {p.Name}"); } } else { Console.WriteLine("Installed packages: (none)"); } } } }
private void _packageList_PackageButtonClick(object sender, PackageControlButtonEventArgs e) { _restartPending = true; switch (e.Button) { case PackageControlButton.Enable: case PackageControlButton.Disable: PackageRegistry.EnablePackage(_context, e.Package.Id, e.Button == PackageControlButton.Enable); break; case PackageControlButton.Uninstall: PackageRegistry.QueueUninstall(_context, e.Package.Id); break; case PackageControlButton.Update: case PackageControlButton.Install: QueueUpdate(e.Package); break; } LoadCategory(_lastCategory); }
public IDisposable Load() { var facility = new BottlesServicePackageFacility(); PackageRegistry.LoadPackages(x => x.Facility(facility)); PackageRegistry.AssertNoFailures(); _services = facility.Services(); if (!_services.Any()) { throw new ApplicationException("No services were detected. Shutting down."); } var tasks = _services.Select(x => x.ToTask()).ToArray(); _services.Each(x => EventAggregator.Messaging.AddListener(x)); tasks.Each(x => x.Start()); Task.WaitAll(tasks); return(this); }
static void Main(string[] args) { var service1Path = Environment.CurrentDirectory.ParentDirectory() .ParentDirectory() .ParentDirectory() .AppendPath("ApplicationLoaderService", "bin", "Debug"); var service2Path = Environment.CurrentDirectory.ParentDirectory() .ParentDirectory() .ParentDirectory() .AppendPath("ApplicationSourceService", "bin", "Debug"); new LinkCommand().Execute(new LinkInput { AppFolder = Environment.CurrentDirectory, CleanAllFlag = true }); new LinkCommand().Execute(new LinkInput { AppFolder = Environment.CurrentDirectory, BottleFolder = service1Path, RemoteFlag = true }); new LinkCommand().Execute(new LinkInput { AppFolder = Environment.CurrentDirectory, BottleFolder = service2Path, RemoteFlag = true }); PackageRegistry.LoadPackages(x => {}); Console.WriteLine("Press any key to quit"); Console.ReadLine(); }
static void Main(string[] args) { var manifest = new LinkManifest(); manifest.AddRemoteLink(new RemoteLink { Folder = "../../../BottleService1", BootstrapperName = "BottleService1.BottleService1Bootstrapper, BottleService1" }); manifest.AddRemoteLink(new RemoteLink { Folder = "../../../BottleService2", BootstrapperName = "BottleService2.BottleService2Bootstrapper, BottleService2" }); manifest.AddRemoteLink(new RemoteLink { Folder = "../../../BottleService3", BootstrapperName = "BottleService3.BottleService3Bootstrapper, BottleService3" }); new FileSystem().WriteObjectToFile(LinkManifest.FILE, manifest); PackageRegistry.LoadPackages(x => { }); PackageRegistry.AssertNoFailures(); Console.WriteLine("Type anything to quit"); Console.ReadLine(); }
private void FindUpdates(SynchronizationContext synchronizationContext) { try { var context = new ContextName(_env.ContextName, _env.Experimental); var installedPackages = PackageRegistry.GetInstalledPackages(context); var packages = NuGetQuerier.GetUpdates( context, _env.NuGetSite, PackageStability.StableOnly, installedPackages.Packages ); synchronizationContext.Post( p => CreateNotifications(packages), null ); } catch (Exception ex) { Log.Warn("Could not find updates", ex); } }
public void activators_should_run_if_all_environment_checks_pass() { var activator = new FakeActivator(); activator.SucceedWith("good"); activator.SucceedWith("better"); activator.SucceedWith("best"); var activator2 = new FakeActivator(); var activator3 = new FakeActivator(); PackageRegistry.LoadPackages(x => { x.Activator(activator); x.Activator(activator2); x.Activator(activator3); }); PackageRegistry.AssertNoFailures(); activator.WasActivated.ShouldBeTrue(); activator2.WasActivated.ShouldBeTrue(); activator3.WasActivated.ShouldBeTrue(); }
public JupyterRequestContextHandler(PackageRegistry packageRegistry) { _packageRegistry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry)); }
public static async Task <int> Do( VerifyOptions verifyOptions, IConsole console, StartupOptions startupOptions = null) { var directoryAccessor = verifyOptions.RootDirectory; var packageRegistry = PackageRegistry.CreateForTryMode(directoryAccessor); var markdownProject = new MarkdownProject( directoryAccessor, packageRegistry, startupOptions); var errorCount = 0; var workspaceServer = new Lazy <IWorkspaceServer>(() => new WorkspaceServerMultiplexer(packageRegistry)); var markdownFiles = markdownProject.GetAllMarkdownFiles().ToArray(); if (markdownFiles.Length == 0) { console.Error.WriteLine($"No markdown files found under {directoryAccessor.GetFullyQualifiedRoot()}"); return(-1); } foreach (var markdownFile in markdownFiles) { var fullName = directoryAccessor.GetFullyQualifiedPath(markdownFile.Path).FullName; var markdownFileDirectoryAccessor = directoryAccessor.GetDirectoryAccessorForRelativePath(markdownFile.Path.Directory); console.Out.WriteLine(); console.Out.WriteLine(fullName); console.Out.WriteLine(new string('-', fullName.Length)); var codeLinkBlocks = await markdownFile.GetAnnotatedCodeBlocks(); var sessions = codeLinkBlocks.GroupBy(block => block.Annotations?.Session); foreach (var session in sessions) { if (session.Select(block => block.ProjectOrPackageName()).Distinct().Count() != 1) { SetError(); console.Out.WriteLine($"Session cannot span projects or packages: --session {session.Key}"); continue; } foreach (var codeLinkBlock in session) { ReportCodeLinkageResults(codeLinkBlock, markdownFileDirectoryAccessor); } Console.ResetColor(); if (!session.Any(block => block.Diagnostics.Any())) { var(buffersToInclude, filesToInclude) = await markdownFile.GetIncludes(markdownFileDirectoryAccessor); await ReportCompileResults( session, markdownFile, filesToInclude, buffersToInclude, markdownFileDirectoryAccessor); } Console.ResetColor(); } } if (errorCount > 0) { SetError(false); } else { SetOk(); } console.Out.WriteLine($"\n\ndotnet try verify found {errorCount} error(s)"); Console.ResetColor(); return(errorCount == 0 ? 0 : 1); void SetError(bool incrementCount = true) { Console.ForegroundColor = ConsoleColor.Red; if (incrementCount) { errorCount++; } } void SetOk() { Console.ForegroundColor = ConsoleColor.Green; } async Task ReportCompileResults( IGrouping <string, AnnotatedCodeBlock> session, MarkdownFile markdownFile, Dictionary <string, File[]> filesToInclude, IReadOnlyDictionary <string, Buffer[]> buffersToInclude, IDirectoryAccessor accessor) { var description = session.Count() == 1 || string.IsNullOrWhiteSpace(session.Key) ? $"region \"{session.Select(s => s.Annotations.Region).Distinct().First()}\"" : $"session \"{session.Key}\""; console.Out.WriteLine($"\n Compiling samples for {description}\n"); var projectOrPackageName = session .Select(b => b.ProjectOrPackageName()) .FirstOrDefault(name => !string.IsNullOrWhiteSpace(name)); var language = session .Select(b => b.Language()) .FirstOrDefault(name => !string.IsNullOrWhiteSpace(name)); if (!ProjectIsCompatibleWithLanguage(new UriOrFileInfo(projectOrPackageName), language)) { SetError(); console.Out.WriteLine($" Build failed as project {projectOrPackageName} is not compatible with language {language}"); } var editableCodeBlocks = session.Where(b => b.Annotations.Editable).ToList(); var buffers = editableCodeBlocks .Select(block => block.GetBufferAsync(accessor, markdownFile)) .ToList(); var files = new List <File>(); if (filesToInclude.TryGetValue("global", out var globalIncludes)) { files.AddRange(globalIncludes); } if (!string.IsNullOrWhiteSpace(session.Key) && filesToInclude.TryGetValue(session.Key, out var sessionIncludes)) { files.AddRange(sessionIncludes); } if (buffersToInclude.TryGetValue("global", out var globalSessionBuffersToInclude)) { buffers.AddRange(globalSessionBuffersToInclude); } if (!string.IsNullOrWhiteSpace(session.Key) && buffersToInclude.TryGetValue(session.Key, out var localSessionBuffersToInclude)) { buffers.AddRange(localSessionBuffersToInclude); } var workspace = new Workspace( workspaceType: projectOrPackageName, language: language, files: files.ToArray(), buffers: buffers.ToArray()); var mergeTransformer = new CodeMergeTransformer(); var inliningTransformer = new BufferInliningTransformer(); var processed = await mergeTransformer.TransformAsync(workspace); processed = await inliningTransformer.TransformAsync(processed); processed = new Workspace(usings: processed.Usings, workspaceType: processed.WorkspaceType, language: processed.Language, files: processed.Files); var result = await workspaceServer.Value.Compile(new WorkspaceRequest(processed)); var projectDiagnostics = result.GetFeature <ProjectDiagnostics>() .Where(e => e.Severity == DiagnosticSeverity.Error) .ToArray(); if (projectDiagnostics.Any()) { SetError(); console.Out.WriteLine($" Build failed for project {projectOrPackageName}"); foreach (var diagnostic in projectDiagnostics) { console.Out.WriteLine($"\t\t{diagnostic.Location}: {diagnostic.Message}"); } } else { var symbol = !result.Succeeded ? "X" : "✓"; if (result.Succeeded) { SetOk(); console.Out.WriteLine($" {symbol} No errors found within samples for {description}"); } else { SetError(); console.Out.WriteLine($" {symbol} Errors found within samples for {description}"); foreach (var diagnostic in result.GetFeature <Diagnostics>()) { console.Out.WriteLine($"\t\t{diagnostic.Message}"); } } } } void ReportCodeLinkageResults( AnnotatedCodeBlock codeLinkBlock, IDirectoryAccessor accessor) { var diagnostics = codeLinkBlock.Diagnostics.ToArray(); Console.ResetColor(); console.Out.WriteLine(" Checking Markdown..."); if (diagnostics.Any()) { SetError(); } else { Console.ForegroundColor = ConsoleColor.Green; } var blockOptions = (LocalCodeBlockAnnotations)codeLinkBlock.Annotations; var file = blockOptions?.SourceFile ?? blockOptions?.DestinationFile; var fullyQualifiedPath = file != null ? accessor.GetFullyQualifiedPath(file).FullName : "UNKNOWN"; var project = codeLinkBlock.ProjectOrPackageName() ?? "UNKNOWN"; var symbol = diagnostics.Any() ? "X" : "✓"; console.Out.WriteLine($" {symbol} Line {codeLinkBlock.Line + 1}:\t{fullyQualifiedPath} (in project {project})"); foreach (var diagnostic in diagnostics) { console.Out.WriteLine($"\t\t{diagnostic}"); } } }
public DocumentationController(MarkdownProject markdownProject, StartupOptions startupOptions, PackageRegistry packageRegistry) { _markdownProject = markdownProject ?? throw new ArgumentNullException(nameof(markdownProject)); _startupOptions = startupOptions; _packageRegistry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry)); }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Demo demo = null, TryGitHub tryGithub = null, Pack pack = null, Install install = null, Verify verify = null, Jupyter jupyter = null, StartKernelServer startKernelServer = null, ITelemetry telemetry = null, IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } startServer = startServer ?? ((startupOptions, invocationContext) => Program.ConstructWebHost(startupOptions).Run()); jupyter = jupyter ?? ((startupOptions, console, server, context) => JupyterCommand.Do(startupOptions, console, server, context)); demo = demo ?? DemoCommand.Do; tryGithub = tryGithub ?? ((repo, console) => GitHubHandler.Handler(repo, console, new GitHubRepoLocator())); verify = verify ?? ((options, console, startupOptions) => VerifyCommand.Do(options, console, startupOptions)); pack = pack ?? PackCommand.Do; install = install ?? InstallCommand.Do; startKernelServer = startKernelServer ?? ((startupOptions, kernel, console) => KernelServerCommand.Do(startupOptions, kernel, console)); // Setup first time use notice sentinel. firstTimeUseNoticeSentinel = firstTimeUseNoticeSentinel ?? new FirstTimeUseNoticeSentinel(); // Setup telemetry. telemetry = telemetry ?? new Telemetry.Telemetry(firstTimeUseNoticeSentinel); var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); Action <ParseResult> track = o => telemetry.SendFiltered(filter, o); var dirArgument = new Argument <FileSystemDirectoryAccessor>(() => new FileSystemDirectoryAccessor(Directory.GetCurrentDirectory())) { Name = nameof(StartupOptions.RootDirectory), Arity = ArgumentArity.ZeroOrOne, Description = "Specify the path to the root directory for your documentation", }; dirArgument.AddValidator(symbolResult => { var directory = symbolResult.Tokens .Select(t => t.Value) .FirstOrDefault(); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { return($"Directory does not exist: {directory}"); } return(null); }); var rootCommand = StartInTryMode(); rootCommand.AddCommand(StartInHostedMode()); rootCommand.AddCommand(Demo()); rootCommand.AddCommand(GitHub()); rootCommand.AddCommand(Pack()); rootCommand.AddCommand(Install()); rootCommand.AddCommand(Verify()); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(KernelServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { // If sentinel does not exist, print the welcome message showing the telemetry notification. if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience) { context.Console.Out.WriteLine(); context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage); firstTimeUseNoticeSentinel.CreateIfNotExists(); } if (context.ParseResult.Directives.Contains("debug") && !(Clock.Current is VirtualClock)) { VirtualClock.Start(); } await next(context); }) .Build()); RootCommand StartInTryMode() { var command = new RootCommand { Name = "dotnet-try", Description = "Interactive documentation in your browser" }; command.AddArgument(dirArgument); command.AddOption(new Option( "--add-package-source", "Specify an additional NuGet package source") { Argument = new Argument <PackageSource>(() => new PackageSource(Directory.GetCurrentDirectory())) { Name = "NuGet source" } }); command.AddOption(new Option( "--package", "Specify a Try .NET package or path to a .csproj to run code samples with") { Argument = new Argument <string> { Name = "name or .csproj" } }); command.AddOption(new Option( "--package-version", "Specify a Try .NET package version to use with the --package option") { Argument = new Argument <string> { Name = "version" } }); command.AddOption(new Option( "--uri", "Specify a URL or a relative path to a Markdown file") { Argument = new Argument <Uri>() }); command.AddOption(new Option( "--enable-preview-features", "Enable preview features") { Argument = new Argument <bool>() }); command.AddOption(new Option( "--log-path", "Enable file logging to the specified directory") { Argument = new Argument <DirectoryInfo> { Name = "dir" } }); command.AddOption(new Option( "--verbose", "Enable verbose logging to the console") { Argument = new Argument <bool>() }); var portArgument = new Argument <ushort>(); portArgument.AddValidator(symbolResult => { if (symbolResult.Tokens .Select(t => t.Value) .Count(value => !ushort.TryParse(value, out _)) > 0) { return("Invalid argument for --port option"); } return(null); }); command.AddOption(new Option( "--port", "Specify the port for dotnet try to listen on") { Argument = portArgument }); command.Handler = CommandHandler.Create <InvocationContext, StartupOptions>((context, options) => { services.AddSingleton(_ => PackageRegistry.CreateForTryMode( options.RootDirectory, options.AddPackageSource)); startServer(options, context); }); return(command); } Command StartInHostedMode() { var command = new Command("hosted") { new Option( "--id", "A unique id for the agent instance (e.g. its development environment id).") { Argument = new Argument <string>(defaultValue: () => Environment.MachineName) }, new Option( "--production", "Specifies whether the agent is being run using production resources") { Argument = new Argument <bool>() }, new Option( "--language-service", "Specifies whether the agent is being run in language service-only mode") { Argument = new Argument <bool>() }, new Option( new[] { "-k", "--key" }, "The encryption key") { Argument = new Argument <string>() }, new Option( new[] { "--ai-key", "--application-insights-key" }, "Application Insights key.") { Argument = new Argument <string>() }, new Option( "--region-id", "A unique id for the agent region") { Argument = new Argument <string>() }, new Option( "--log-to-file", "Writes a log file") { Argument = new Argument <bool>() } }; command.Description = "Starts the Try .NET agent"; command.IsHidden = true; command.Handler = CommandHandler.Create <InvocationContext, StartupOptions>((context, options) => { services.AddSingleton(_ => PackageRegistry.CreateForHostedMode()); services.AddSingleton(c => new MarkdownProject(c.GetRequiredService <PackageRegistry>())); services.AddSingleton <IHostedService, Warmup>(); startServer(options, context); }); return(command); } Command Demo() { var demoCommand = new Command( "demo", "Learn how to create Try .NET content with an interactive demo") { new Option("--output", "Where should the demo project be written to?") { Argument = new Argument <DirectoryInfo>( defaultValue: () => new DirectoryInfo(Directory.GetCurrentDirectory())) } }; demoCommand.Handler = CommandHandler.Create <DemoOptions, InvocationContext>((options, context) => { demo(options, context.Console, startServer, context); }); return(demoCommand); } Command GitHub() { var argument = new Argument <string> { // System.CommandLine parameter binding does lookup by name, // so name the argument after the github command's string param Name = nameof(TryGitHubOptions.Repo) }; var github = new Command("github", "Try a GitHub repo") { argument }; github.IsHidden = true; github.Handler = CommandHandler.Create <TryGitHubOptions, IConsole>((repo, console) => tryGithub(repo, console)); return(github); } Command Jupyter() { var jupyterCommand = new Command("jupyter", "Starts dotnet try as a Jupyter kernel"); var defaultKernelOption = new Option("--default-kernel", "The default .NET kernel language for the notebook.") { Argument = new Argument <string>(defaultValue: () => "csharp") }; jupyterCommand.AddOption(defaultKernelOption); var connectionFileArgument = new Argument <FileInfo> { Name = "ConnectionFile", Arity = ArgumentArity.ZeroOrOne //should be removed once the commandlineapi allows subcommands to not have arguments from the main command }.ExistingOnly(); jupyterCommand.AddArgument(connectionFileArgument); jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext>((startupOptions, options, console, context) => { track(context.ParseResult); services .AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton( c => { return(CommandScheduler .Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >() .Trace() .Handle(delivery))); }) .AddSingleton(c => CreateKernel(options.DefaultKernel)) .AddSingleton(c => new JupyterRequestContextHandler(c.GetRequiredService <IKernel>()) .Trace()) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>(); return(jupyter(startupOptions, console, startServer, context)); }); var installCommand = new Command("install", "Install the .NET kernel for Jupyter"); installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext>((console, context) => { track(context.ParseResult); return(new JupyterCommandLine(console, new FileSystemJupyterKernelSpec()).InvokeAsync()); }); jupyterCommand.AddCommand(installCommand); return(jupyterCommand); } Command KernelServer() { var startKernelServerCommand = new Command("kernel-server", "Starts dotnet-try with kernel functionality exposed over standard I/O"); var defaultKernelOption = new Option("--default-kernel", "The default .NET kernel language for the notebook.") { Argument = new Argument <string>(defaultValue: () => "csharp") }; startKernelServerCommand.AddOption(defaultKernelOption); startKernelServerCommand.Handler = CommandHandler.Create <StartupOptions, KernelServerOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { track(context.ParseResult); return(startKernelServer(startupOptions, CreateKernel(options.DefaultKernel), console)); }); return(startKernelServerCommand); } Command Pack() { var packCommand = new Command("pack", "Create a Try .NET package") { new Argument <DirectoryInfo> { Name = nameof(PackOptions.PackTarget) }, new Option("--version", "The version of the Try .NET package") { Argument = new Argument <string>() }, new Option("--enable-wasm", "Enables web assembly code execution") }; packCommand.IsHidden = true; packCommand.Handler = CommandHandler.Create <PackOptions, IConsole>( (options, console) => { return(pack(options, console)); }); return(packCommand); } Command Install() { var installCommand = new Command("install", "Install a Try .NET package") { new Argument <string> { Name = nameof(InstallOptions.PackageName), Arity = ArgumentArity.ExactlyOne }, new Option("--add-source") { Argument = new Argument <PackageSource>() } }; installCommand.IsHidden = true; installCommand.Handler = CommandHandler.Create <InstallOptions, IConsole>((options, console) => install(options, console)); return(installCommand); } Command Verify() { var verifyCommand = new Command("verify", "Verify Markdown files in the target directory and its children.") { dirArgument }; verifyCommand.Handler = CommandHandler.Create <VerifyOptions, IConsole, StartupOptions>( (options, console, startupOptions) => { return(verify(options, console, startupOptions)); }); return(verifyCommand); } }
public static void Start() { FubuApplication.For <Conventions>().StructureMap(new Container()).Bootstrap(); PackageRegistry.AssertNoFailures(); }
public PackagesController(PackageRegistry registry) { _registry = registry; }