Ejemplo n.º 1
0
        private async Task HandleSubmitCode(
            SubmitCode submitCode,
            KernelInvocationContext context)
        {
            CancellationTokenSource cancellationSource;

            lock (_cancellationSourceLock)
            {
                cancellationSource = _cancellationSource;
            }

            var codeSubmissionReceived = new CodeSubmissionReceived(submitCode);

            context.Publish(codeSubmissionReceived);

            var code       = submitCode.Code;
            var isComplete = await IsCompleteSubmissionAsync(submitCode.Code);

            if (isComplete)
            {
                context.Publish(new CompleteCodeSubmissionReceived(submitCode));
            }
            else
            {
                context.Publish(new IncompleteCodeSubmissionReceived(submitCode));
            }

            if (submitCode.SubmissionType == SubmissionType.Diagnose)
            {
                return;
            }

            Exception exception = null;

            using var console = await ConsoleOutput.Capture();

            using (console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode)))
                using (console.SubscribeToStandardError(std => PublishError(std, context, submitCode)))
                {
                    if (!cancellationSource.IsCancellationRequested)
                    {
                        try
                        {
                            if (ScriptState == null)
                            {
                                ScriptState = await CSharpScript.RunAsync(
                                    code,
                                    ScriptOptions,
                                    cancellationToken : cancellationSource.Token)
                                              .UntilCancelled(cancellationSource.Token);
                            }
                            else
                            {
                                ScriptState = await ScriptState.ContinueWithAsync(
                                    code,
                                    ScriptOptions,
                                    catchException :  e =>
                                {
                                    exception = e;
                                    return(true);
                                },
                                    cancellationToken : cancellationSource.Token)
                                              .UntilCancelled(cancellationSource.Token);
                            }
                        }
                        catch (CompilationErrorException cpe)
                        {
                            exception = new CodeSubmissionCompilationErrorException(cpe);
                        }
                        catch (Exception e)
                        {
                            exception = e;
                        }
                    }
                }

            if (!cancellationSource.IsCancellationRequested)
            {
                if (exception != null)
                {
                    string message = null;

                    if (exception is CodeSubmissionCompilationErrorException compilationError)
                    {
                        message =
                            string.Join(Environment.NewLine,
                                        (compilationError.InnerException as CompilationErrorException)?.Diagnostics.Select(d => d.ToString()) ?? Enumerable.Empty <string>());
                    }

                    context.Fail(exception, message);
                }
                else
                {
                    if (ScriptState != null && HasReturnValue)
                    {
                        var formattedValues = FormattedValue.FromObject(ScriptState.ReturnValue);
                        context.Publish(
                            new ReturnValueProduced(
                                ScriptState.ReturnValue,
                                submitCode,
                                formattedValues));
                    }
                }
            }
            else
            {
                context.Fail(null, "Command cancelled");
            }
        }
Ejemplo n.º 2
0
 private static bool StandardInputIsAllowed(KernelInvocationContext context)
 {
     return(context?.HandlingKernel is { } kernel&& kernel.FrontendEnvironment.AllowStandardInput);
 }
Ejemplo n.º 3
0
        protected override async Task HandleSubmitCode(
            SubmitCode submitCode,
            KernelInvocationContext context)
        {
            var codeSubmissionReceived = new CodeSubmissionReceived(submitCode);

            context.Publish(codeSubmissionReceived);

            var code       = submitCode.Code;
            var isComplete = await IsCompleteSubmissionAsync(submitCode.Code);

            if (isComplete)
            {
                context.Publish(new CompleteCodeSubmissionReceived(submitCode));
            }
            else
            {
                context.Publish(new IncompleteCodeSubmissionReceived(submitCode));
            }

            if (submitCode.SubmissionType == SubmissionType.Diagnose)
            {
                return;
            }

            Exception exception = null;

            if (!context.CancellationToken.IsCancellationRequested)
            {
                ScriptOptions = ScriptOptions.WithMetadataResolver(
                    ScriptMetadataResolver.Default.WithBaseDirectory(
                        Directory.GetCurrentDirectory()));

                try
                {
                    if (ScriptState == null)
                    {
                        ScriptState = await CSharpScript.RunAsync(
                            code,
                            ScriptOptions,
                            cancellationToken : context.CancellationToken)
                                      .UntilCancelled(context.CancellationToken);
                    }
                    else
                    {
                        ScriptState = await ScriptState.ContinueWithAsync(
                            code,
                            ScriptOptions,
                            catchException : e =>
                        {
                            exception = e;
                            return(true);
                        },
                            cancellationToken : context.CancellationToken)
                                      .UntilCancelled(context.CancellationToken);
                    }
                }
                catch (CompilationErrorException cpe)
                {
                    exception = new CodeSubmissionCompilationErrorException(cpe);
                }
                catch (Exception e)
                {
                    exception = e;
                }
            }

            if (!context.CancellationToken.IsCancellationRequested)
            {
                if (exception != null)
                {
                    string message = null;

                    if (exception is CodeSubmissionCompilationErrorException compilationError)
                    {
                        message =
                            string.Join(Environment.NewLine,
                                        (compilationError.InnerException as CompilationErrorException)?.Diagnostics.Select(d => d.ToString()) ?? Enumerable.Empty <string>());
                    }

                    context.Fail(exception, message);
                }
                else
                {
                    if (ScriptState != null && HasReturnValue)
                    {
                        var formattedValues = FormattedValue.FromObject(ScriptState.ReturnValue);
                        context.Publish(
                            new ReturnValueProduced(
                                ScriptState.ReturnValue,
                                submitCode,
                                formattedValues));
                    }
                }
            }
            else
            {
                context.Fail(null, "Command cancelled");
            }
        }
Ejemplo n.º 4
0
 public Task HandleAsync(RequestCompletions command, KernelInvocationContext context) => HandleRequestCompletionAsync(command, context);
Ejemplo n.º 5
0
 public Task HandleAsync(SubmitCode command, KernelInvocationContext context) => HandleSubmitCodeAsync(command, context);
Ejemplo n.º 6
0
 public override Task <Kernel> CreateKernelAsync(FakeKernelConnectionOptions options, KernelInvocationContext context)
 {
     return(CreateKernel(options, context));
 }
Ejemplo n.º 7
0
        private async Task InitializeDbContextAsync(string kernelName, MsSqlKernelConnector options, KernelInvocationContext context)
        {
            CSharpKernel csharpKernel = null;

            context.HandlingKernel.VisitSubkernelsAndSelf(k =>
            {
                if (k is CSharpKernel csk)
                {
                    csharpKernel = csk;
                }
            });

            if (csharpKernel is null)
            {
                return;
            }

            context.DisplayAs($"Scaffolding a `DbContext` and initializing an instance of it called `{kernelName}` in the C# kernel.", "text/markdown");

            var submission1 = @$ "
#r " "nuget: Microsoft.EntityFrameworkCore.Design, 6.0.0" "
#r " "nuget: Microsoft.EntityFrameworkCore.SqlServer, 6.0.0" "
#r " "nuget: Humanizer.Core, 2.8.26" "
#r " "nuget: Humanizer, 2.8.26" "

            using System;
using System.Reflection;
using System.Linq;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Scaffolding;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddEntityFrameworkDesignTimeServices();
var providerAssembly = Assembly.Load(" "Microsoft.EntityFrameworkCore.SqlServer" ");
var providerServicesAttribute = providerAssembly.GetCustomAttribute<DesignTimeProviderServicesAttribute>();
var providerServicesType = providerAssembly.GetType(providerServicesAttribute.TypeName);
var providerServices = (IDesignTimeServices)Activator.CreateInstance(providerServicesType);
providerServices.ConfigureDesignTimeServices(services);

var serviceProvider = services.BuildServiceProvider();
var scaffolder = serviceProvider.GetService<IReverseEngineerScaffolder>();

var model = scaffolder.ScaffoldModel(
    @" "{options.ConnectionString}" ",
    new DatabaseModelFactoryOptions(),
    new ModelReverseEngineerOptions(),
    new ModelCodeGenerationOptions()
    {{
        ContextName = " "{kernelName}Context" ",
        ModelNamespace = " "{kernelName}" "
    }});
        private async Task LoadFromAssembly(
            FileInfo assemblyFile,
            Kernel kernel,
            KernelInvocationContext context)
        {
            if (assemblyFile == null)
            {
                throw new ArgumentNullException(nameof(assemblyFile));
            }

            if (kernel == null)
            {
                throw new ArgumentNullException(nameof(kernel));
            }

            if (!assemblyFile.Exists)
            {
                throw new ArgumentException($"File {assemblyFile.FullName} doesn't exist", nameof(assemblyFile));
            }

            bool loadExtensions;

            lock (_lock)
            {
                loadExtensions = _loadedAssemblies.Add(AssemblyName.GetAssemblyName(assemblyFile.FullName));
            }

            if (loadExtensions)
            {
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile.FullName);

                var extensionTypes = assembly
                                     .ExportedTypes
                                     .Where(t => t.CanBeInstantiated() && typeof(IKernelExtension).IsAssignableFrom(t))
                                     .ToArray();

                foreach (var extensionType in extensionTypes)
                {
                    var extension = (IKernelExtension)Activator.CreateInstance(extensionType);

                    var displayed = context.Display(
                        $"Loading kernel extension \"{extensionType.Name}\" from assembly {assemblyFile.FullName}");

                    try
                    {
                        await extension.OnLoadAsync(kernel);

                        context.Publish(new KernelExtensionLoaded(extension));
                        displayed.Update($"Loaded {extension}");
                    }
                    catch (Exception e)
                    {
                        context.Publish(new ErrorProduced(
                                            $"Failed to load kernel extension \"{extensionType.Name}\" from assembly {assemblyFile.FullName}",
                                            context.Command));

                        context.Fail(new KernelExtensionLoadException(e));
                    }
                }
            }
        }
Ejemplo n.º 9
0
 protected override Task HandleRequestCompletion(RequestCompletion command, KernelInvocationContext context)
 {
     Handle(command, context);
     return(Task.CompletedTask);
 }
Ejemplo n.º 10
0
 protected override Task HandleSubmitCode(SubmitCode command, KernelInvocationContext context)
 {
     Handle(command, context);
     return(Task.CompletedTask);
 }
Ejemplo n.º 11
0
 public override Task InvokeAsync(KernelInvocationContext context)
 {
     Directory.SetCurrentDirectory(WorkingDirectory);
     context.Publish(new WorkingDirectoryChanged(WorkingDirectory, this));
     return(Task.CompletedTask);
 }
Ejemplo n.º 12
0
 public override Task <Kernel> ConnectKernelAsync(KernelInfo kernelInfo, FakeKernelConnector connector,
                                                  KernelInvocationContext context)
 {
     connector.CreateKernel = (name) => CreateKernel(name, connector, context);
     return(connector.ConnectKernelAsync(kernelInfo));
 }