private static async Task GenerateClass(KernelInvocationContext context,
                                                IFileReader fileReader,
                                                IGeneratorConfiguration config)
        {
            var classGenerator = new ClassGenerator();
            var className      = Path.GetFileNameWithoutExtension(fileReader.FileName);

            className = char.ToUpper(className[0]) + className.Substring(1);
            context.Display($"Generating class {className}", new[] { "text/html" });
            var source = classGenerator.GenerateFile(fileReader.FileMetaData, config);
            var result = await context.HandlingKernel.SubmitCodeAsync(source);

            result.KernelEvents.Subscribe((ev) => { }, (ex) =>
            {
                context.Display(ex.Message, new[] { "text/plain" });
            });
            result.KernelEvents.Subscribe((ev) =>
            {
                if (ev is ErrorProduced error)
                {
                    context.Fail(context.Command, null, error.Message);
                }
                if (ev is CommandFailed failure)
                {
                    context.Fail(context.Command, null, failure.Message);
                }
            });
        }
예제 #2
0
        private async Task LoadFromAssembly(
            FileInfo assemblyFile,
            IKernel 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 display   = Guid.NewGuid().ToString("N");
                    context.Publish(new DisplayedValueProduced(
                                        $"Loading kernel extension {extensionType.Name} from assembly {assemblyFile.FullName}",
                                        context.Command, valueId: display));
                    try
                    {
                        await extension.OnLoadAsync(kernel);

                        context.Publish(new DisplayedValueUpdated(
                                            $"Loaded kernel extension {extensionType.Name} from assembly {assemblyFile.FullName}",
                                            display, context.Command));
                    }
                    catch (Exception e)
                    {
                        context.Publish(new ErrorProduced(
                                            $"Failure loading kernel extension {extensionType.Name} from assembly {assemblyFile.FullName}",
                                            context.Command));
                        context.Fail(new KernelExtensionLoadException(e));
                    }
                }
            }
        }
예제 #3
0
 public override async Task InvokeAsync(KernelInvocationContext context)
 {
     if (context.HandlingKernel is IExtensibleKernel extensibleKernel)
     {
         await extensibleKernel.LoadExtensionsFromDirectory(
             Directory,
             context,
             AdditionalDependencies);
     }
     else
     {
         context.Fail(
             message: $"Kernel {context.HandlingKernel.Name} doesn't support loading extensions");
     }
 }
예제 #4
0
        private void Inspect(OptimizationLevel configuration, SourceCodeKind kind, Platform platform, KernelInvocationContext context)
        {
            if (!(context.Command is SubmitCode))
            {
                return;
            }

            var command = context.Command as SubmitCode;

            // TODO: Is there a proper way of cleaning up code from the magic commands?
            var code = Regex.Replace(command.Code, $"#!{INSPECT_COMMAND}(.*)", "");

            var options = new InspectionOptions
            {
                CompilationLanguage   = InspectionOptions.LanguageVersion.CSHARP_PREVIEW,
                DecompilationLanguage = InspectionOptions.LanguageVersion.CSHARP_PREVIEW,
                Kind = kind,
                OptimizationLevel = configuration,
                Platform          = Platform.AnyCpu
            };

            var inspect = Inspector.Inspector.Create(options);

            var result = inspect.Compile(code);

            if (!result.IsSuccess)
            {
                var diagnostics = string.Join('\n', result.CompilationDiagnostics);
                context.Fail(message: $"Uh-oh, something went wrong:\n {diagnostics}");
                return;
            }

            var htmlResults = RenderResultInTabs(result.CSharpDecompilation, result.ILDecompilation, result.JitDecompilation);

            context.Publish(
                new DisplayedValueProduced(
                    htmlResults,
                    context.Command,
                    new[]
            {
                new FormattedValue("text/html", htmlResults.ToString())
            }));
        }
예제 #5
0
        public override async Task InvokeAsync(KernelInvocationContext context)
        {
            if (context.HandlingKernel is IExtensibleKernel extensibleKernel)
            {
                await extensibleKernel.LoadExtensionsFromDirectory(
                    Directory,
                    context,
                    AdditionalDependencies);
            }
            else
            {
                context.Fail(
                    message: $"Kernel {context.HandlingKernel.Name} doesn't support loading extensions");
            }

            await context.HandlingKernel.VisitSubkernelsAsync(async k =>
            {
                var src     = context.Command as LoadKernelExtensionsInDirectory;
                var command = new LoadKernelExtensionsInDirectory(src.Directory, src.AdditionalDependencies);
                await k.SendAsync(command);
            });
        }
예제 #6
0
        public async Task HandleAsync(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;
            string    message   = null;

            if (!context.CancellationToken.IsCancellationRequested)
            {
                try
                {
                    await RunAsync(
                        code,
                        context.CancellationToken,
                        e =>
                    {
                        exception = e;
                        return(true);
                    });
                }
                catch (CompilationErrorException cpe)
                {
                    exception = new CodeSubmissionCompilationErrorException(cpe);
                }
                catch (Exception e)
                {
                    exception = e;
                }
            }

            if (!context.CancellationToken.IsCancellationRequested)
            {
                var diagnostics = ImmutableArray <CodeAnalysis.Diagnostic> .Empty;

                // Check for a compilation failure
                if (exception is CodeSubmissionCompilationErrorException compilationError &&
                    compilationError.InnerException is CompilationErrorException innerCompilationException)
                {
                    diagnostics = innerCompilationException.Diagnostics;
                    // In the case of an error the diagnostics get attached to both the
                    // DiagnosticsProduced and CommandFailed events.
                    message =
                        string.Join(Environment.NewLine,
                                    innerCompilationException.Diagnostics.Select(d => d.ToString()) ?? Enumerable.Empty <string>());
                }
                else
                {
                    diagnostics = ScriptState?.Script.GetCompilation().GetDiagnostics() ?? ImmutableArray <CodeAnalysis.Diagnostic> .Empty;
                }

                // Publish the compilation diagnostics. This doesn't include the exception.
                var kernelDiagnostics = diagnostics.Select(Diagnostic.FromCodeAnalysisDiagnostic).ToImmutableArray();

                var formattedDiagnostics =
                    diagnostics
                    .Select(d => d.ToString())
                    .Select(text => new FormattedValue(PlainTextFormatter.MimeType, text))
                    .ToImmutableArray();

                context.Publish(new DiagnosticsProduced(kernelDiagnostics, submitCode, formattedDiagnostics));

                // Report the compilation failure or exception
                if (exception != null)
                {
                    context.Fail(exception, message);
                }
                else
                {
                    if (ScriptState != null && HasReturnValue)
                    {
                        var formattedValues = FormattedValue.FromObject(ScriptState.ReturnValue);
                        context.Publish(
                            new ReturnValueProduced(
                                ScriptState.ReturnValue,
                                submitCode,
                                formattedValues));
                    }
                }
            }
예제 #7
0
        public async Task HandleAsync(SubmitCode command, KernelInvocationContext context)
        {
            if (!_connected)
            {
                return;
            }

            if (_queryCompletionHandler != null)
            {
                context.Display("Error: Another query is currently running. Please wait for that query to complete before re-running this cell.");
                return;
            }

            var completion = new TaskCompletionSource <bool>();

            _queryCompletionHandler = async queryParams =>
            {
                try
                {
                    foreach (var batchSummary in queryParams.BatchSummaries)
                    {
                        foreach (var resultSummary in batchSummary.ResultSetSummaries)
                        {
                            if (completion.Task.IsCompleted)
                            {
                                return;
                            }

                            var subsetParams = new QueryExecuteSubsetParams()
                            {
                                OwnerUri       = _tempFileUri.ToString(),
                                BatchIndex     = batchSummary.Id,
                                ResultSetIndex = resultSummary.Id,
                                RowsStartIndex = 0,
                                RowsCount      = Convert.ToInt32(resultSummary.RowCount)
                            };
                            var subsetResult = await _serviceClient.ExecuteQueryExecuteSubsetAsync(subsetParams);

                            if (subsetResult.Message != null)
                            {
                                context.Fail(message: subsetResult.Message);
                            }
                            else
                            {
                                var table = GetEnumerableTable(resultSummary.ColumnInfo, subsetResult.ResultSubset.Rows);
                                context.Display(table);
                            }
                        }
                    }
                    completion.SetResult(true);
                }
                catch (Exception e)
                {
                    completion.SetException(e);
                }
            };

#pragma warning disable 1998
            _queryMessageHandler = async messageParams =>
            {
                try
                {
                    if (messageParams.Message.IsError)
                    {
                        context.Fail(message: messageParams.Message.Message);
                        completion.SetResult(true);
                    }
                }
                catch (Exception e)
                {
                    completion.SetException(e);
                }
            };
#pragma warning restore 1998

            try
            {
                await _serviceClient.ExecuteQueryStringAsync(_tempFileUri, command.Code);

                await completion.Task;
            }
            finally
            {
                _queryCompletionHandler = null;
                _queryMessageHandler    = null;
            }
        }
예제 #8
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)
            {
                try
                {
                    await RunAsync(
                        code,
                        context.CancellationToken,
                        e =>
                    {
                        exception = e;
                        return(true);
                    });
                }
                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");
            }
        }
예제 #9
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)
                    {
                        ScriptOptions = ScriptOptions.WithMetadataResolver(
                            ScriptMetadataResolver.Default.WithBaseDirectory(
                                Directory.GetCurrentDirectory()));

                        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");
            }
        }
        private async Task LoadFromAssembly(
            FileInfo assemblyFile,
            Kernel kernel,
            KernelInvocationContext context)
        {
            if (assemblyFile is null)
            {
                throw new ArgumentNullException(nameof(assemblyFile));
            }

            if (kernel is 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();

                if (extensionTypes.Any())
                {
                    context.DisplayAs($"Loading extensions from `{assemblyFile.Name}`", "text/markdown");
                }

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

                    try
                    {
                        await extension.OnLoadAsync(kernel);

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

                        context.Fail(context.Command, new KernelExtensionLoadException(e));
                    }
                }
            }
        }