public async Task Completions_suggest_existing_DataFrame_variables()
        {
            var kernel = new CSharpKernel()
                         .UseNugetDirective();

            await new DataFrameTypeGeneratorExtension().OnLoadAsync(kernel);

            await kernel.SubmitCodeAsync($@"
#r ""{typeof(DataFrame).Assembly.Location}""
using Microsoft.Data.Analysis;
");

            var dataFrameVariableName = "myDataFrame";
            await kernel.SetVariableAsync(dataFrameVariableName, CreateDataFrame());

            var code   = "#!linqify ";
            var result = await kernel.SendAsync(new RequestCompletions(code, new LinePosition(0, code.Length)));

            result.KernelEvents.ToSubscribedList().Should().ContainSingle <CompletionsProduced>()
            .Which
            .Completions
            .Select(c => c.DisplayText)
            .Should()
            .Contain(dataFrameVariableName);
        }
        public static CSharpKernel UseAspNetCore(this CSharpKernel kernel)
        {
            InteractiveHost interactiveHost = null;

            var directive = new Command("#!aspnet", "Activate ASP.NET Core")
            {
                Handler = CommandHandler.Create(async() =>
                {
                    if (interactiveHost is {})
                    {
                        return;
                    }

                    var interactiveLoggerProvider = new InteractiveLoggerProvider();

                    kernel.AddMiddleware(async(command, context, next) =>
                    {
                        // REVIEW: Is there a way to log even when there's no command in progress?
                        // This is currently necessary because the #!log command uses KernelInvocationContext.Current in
                        // its LogEvents.Subscribe callback and KernelInvocationContext.Current is backed by an AsyncLocal.
                        // Is there a way to log to diagnostic output without KernelInvocationContext.Current?
                        using (command is SubmitCode ? interactiveLoggerProvider.SubscribePocketLogerWithCurrentEC() : null)
                        {
                            await next(command, context).ConfigureAwait(false);
                        }
                    });

                    // The middleware doesn't cover the current command's executions so we need this to capture startup logs.
                    using (interactiveLoggerProvider.SubscribePocketLogerWithCurrentEC())
                    {
                        // We could try to manage the host's lifetime, but for now just stop the kernel if you want to stop the host.
                        interactiveHost   = new InteractiveHost(interactiveLoggerProvider);
                        var startHostTask = interactiveHost.StartAsync();

                        var rDirectives = string.Join(Environment.NewLine, _references.Select(a => $"#r \"{a.Location}\""));
                        var usings      = string.Join(Environment.NewLine, _namespaces.Select(ns => $"using {ns};"));

                        await kernel.SendAsync(new SubmitCode($"{rDirectives}{Environment.NewLine}{usings}"), CancellationToken.None).ConfigureAwait(false);

                        await startHostTask.ConfigureAwait(false);

                        var httpClient = HttpClientFormatter.CreateEnhancedHttpClient(interactiveHost.Address, interactiveLoggerProvider);
                        await kernel.SetValueAsync <IApplicationBuilder>("App", interactiveHost.App).ConfigureAwait(false);
                        await kernel.SetValueAsync <IEndpointRouteBuilder>("Endpoints", interactiveHost.Endpoints).ConfigureAwait(false);
                        await kernel.SetValueAsync <HttpClient>("HttpClient", httpClient).ConfigureAwait(false);
                    }
                })
            };
Exemple #3
0
        public async Task It_returns_the_list_of_intrinsic_kernel_commands()
        {
            using var kernel = new CSharpKernel();

            var result = await kernel.SendAsync(new RequestKernelInfo());

            var events = result.KernelEvents.ToSubscribedList();

            events.Should()
            .ContainSingle <KernelInfoProduced>()
            .Which
            .KernelInfo
            .SupportedKernelCommands
            .Select(info => info.Name)
            .Should()
            .Contain(
                nameof(SubmitCode));
        }
Exemple #4
0
        public async Task It_returns_the_list_of_directives_commands()
        {
            using var kernel = new CSharpKernel()
                               .UseNugetDirective()
                               .UseWho();

            var result = await kernel.SendAsync(new RequestKernelInfo());

            var events = result.KernelEvents.ToSubscribedList();

            events.Should()
            .ContainSingle <KernelInfoProduced>()
            .Which
            .KernelInfo
            .SupportedDirectives
            .Select(info => info.Name)
            .Should()
            .Contain("#!who", "#!who", "#r");
        }
        public async Task Script_state_is_available_within_middleware_pipeline()
        {
            var variableCountBeforeEvaluation = 0;
            var variableCountAfterEvaluation  = 0;

            using var kernel = new CSharpKernel();

            kernel.AddMiddleware(async(command, context, next) =>
            {
                var k = context.HandlingKernel as CSharpKernel;

                await next(command, context);

                variableCountAfterEvaluation = k.ScriptState.Variables.Length;
            });

            await kernel.SendAsync(new SubmitCode("var x = 1;"));

            variableCountBeforeEvaluation.Should().Be(0);
            variableCountAfterEvaluation.Should().Be(1);
        }
        public async Task Events_published_by_child_kernel_are_visible_in_parent_kernel()
        {
            var subKernel = new CSharpKernel();

            using var compositeKernel = new CompositeKernel
                  {
                      subKernel
                  };

            var events = compositeKernel.KernelEvents.ToSubscribedList();

            await subKernel.SendAsync(new SubmitCode("var x = 1;"));

            events
            .Select(e => e.GetType())
            .Should()
            .ContainInOrder(
                typeof(CodeSubmissionReceived),
                typeof(CompleteCodeSubmissionReceived),
                typeof(CommandSucceeded));
        }
Exemple #7
0
        private static async Task ConfigureRover(CSharpKernel csharpKernel)
        {
            Microsoft.DotNet.Interactive.Formatting.Formatter.ListExpansionLimit = 42;
            using var _ = Log.OnEnterAndExit();
            await LoadAssemblyAndAddNamespace <RoverRobot>(csharpKernel);
            await LoadAssemblyAndAddNamespace <ResourceScanner>(csharpKernel);
            await AddNamespace(csharpKernel, typeof(ImageProcessing.ImageExtensions));

            var RoverBody = new RoverRobot(PiTop4Board.Instance.GetOrCreateExpansionPlate(),
                                           PiTop4Board.Instance.GetOrCreateCamera <StreamingCamera>(0),
                                           RoverRobotConfiguration.Default);
            var RoverBrain = new RoverRobotAgent();

            var ResourceScanner = new ResourceScanner();

            RoverBody.BlinkAllLights();

            await csharpKernel.SetVariableAsync(nameof(RoverBody), RoverBody);

            await csharpKernel.SetVariableAsync(nameof(RoverBrain), RoverBrain);

            await csharpKernel.SetVariableAsync(nameof(ResourceScanner), ResourceScanner);

            var command = new Command("#!reset", "Reset RoverBody, RoverBrain and BrainState")
            {
                new Option <bool>("--body", description: "Resets the rover body"),
                new Option <bool>("--brain", description: "Resets the rover brain"),
                new Option <bool>("--state", description: "Resets the rover brain state"),
                new Option <bool>("--all", description: "Resets the entire rover"),
            };

            command.Handler = CommandHandler.Create <bool, bool, bool, bool, KernelInvocationContext>(async(body, brain, state, all, context) =>
            {
                if (body || brain || state || all)
                {
                    var code        = new StringBuilder();
                    var resetTarget = new List <string>();
                    if (brain || all)
                    {
                        code.AppendLine($"{nameof(RoverBrain)}.Reset();");
                        resetTarget.Add("brain");
                    }

                    if (state || all)
                    {
                        code.AppendLine($"{nameof(RoverBrain)}.ClearState();");
                        resetTarget.Add("state");
                    }

                    if (body || all)
                    {
                        code.AppendLine($"{nameof(RoverBody)}.Reset();");
                        resetTarget.Add("body");
                    }

                    var value = context.Display($"Reset for {string.Join(", ", resetTarget)} in progress", PlainTextFormatter.MimeType);

                    await csharpKernel.SendAsync(new SubmitCode(code.ToString()));

                    value.Update($"Reset for {string.Join(", ", resetTarget)} done!");
                }
            });

            csharpKernel.AddDirective(command);

            var source = new CancellationTokenSource();

            var robotLoop = Task.Run(() =>
            {
                using var operation = Log.OnEnterAndExit("roverBrainLoop");
                while (!source.IsCancellationRequested)
                {
                    if (!source.IsCancellationRequested)
                    {
                        using var __ = operation.OnEnterAndExit("Perceive");
                        try
                        {
                            RoverBrain.Perceive();
                        }
                        catch (Exception e)
                        {
                            __.Error(e);
                        }
                    }

                    if (!source.IsCancellationRequested)
                    {
                        var planResult = PlanningResult.NoPlan;
                        using var ___  = operation.OnEnterAndExit("Plan");
                        try
                        {
                            planResult = RoverBrain.Plan();
                        }
                        catch (Exception e)
                        {
                            ___.Error(e);
                            planResult = PlanningResult.NoPlan;
                        }

                        if (!source.IsCancellationRequested && planResult != PlanningResult.NoPlan)
                        {
                            using var ____ = operation.OnEnterAndExit("Act");
                            RoverBrain.Act();
                        }
                    }
                }

                RoverBody.MotionComponent.Stop();
            }, source.Token);

            var reactLoop = Task.Run(() =>
            {
                using var operation = Log.OnEnterAndExit("roverBrainReactLoop");
                while (!source.IsCancellationRequested)
                {
                    if (!source.IsCancellationRequested)
                    {
                        using var __ = operation.OnEnterAndExit("React");
                        try
                        {
                            RoverBrain.React();
                        }
                        catch (Exception e)
                        {
                            __.Error(e);
                        }
                    }
                }

                RoverBody.MotionComponent.Stop();
            }, source.Token);

            csharpKernel.RegisterForDisposal(() =>
            {
                source.Cancel(false);
                Task.WaitAll(new[] { robotLoop, reactLoop }, TimeSpan.FromSeconds(10));
                RoverBody.Dispose();
            });
        }
Exemple #8
0
 private static async Task AddNamespace(CSharpKernel csharpKernel, Type type)
 {
     await csharpKernel.SendAsync(new SubmitCode(@$ "using {type.Namespace};"));
 }