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
        public Task HandleAsync(SubmitCode command, KernelInvocationContext context)
        {
            var markdown = new MermaidMarkdown(command.Code);

            context.Display(markdown);
            return(Task.CompletedTask);
        }
예제 #3
0
        private async Task InitializeDbContextAsync(MsSqlConnectionOptions options, KernelInvocationContext context)
        {
            CSharpKernel csharpKernel = null;

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

            if (csharpKernel is null)
            {
                return;
            }

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

            var submission1 = @$ "
#r " "nuget:Microsoft.EntityFrameworkCore.Design,3.1.8" "
#r " "nuget:Microsoft.EntityFrameworkCore.SqlServer,3.1.8" "

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 = " "{options.KernelName}Context" ",
        ModelNamespace = " "{options.KernelName}" "
    }});
예제 #4
0
        public virtual async Task HandleAsync(
            SubmitCode submitCode,
            KernelInvocationContext context)
        {
            await using var connection = OpenConnection();

            if (connection.State != ConnectionState.Open)
            {
                await connection.OpenAsync();
            }

            await using var dbCommand = connection.CreateCommand();

            dbCommand.CommandText = submitCode.Code;

            var results = Execute(dbCommand);

            context.Display(results);
        }
예제 #5
0
        private async Task LoadScriptExtensionFromDirectory(
            DirectoryInfo directory,
            Kernel kernel,
            KernelInvocationContext context)
        {
            var extensionFile = new FileInfo(Path.Combine(directory.FullName, ExtensionScriptName));

            if (extensionFile.Exists)
            {
                var logMessage = $"Loading extension script from `{extensionFile.FullName}`";
                using var op = new ConfirmationLogger(
                          Log.Category,
                          message: logMessage,
                          logOnStart: true,
                          args: new object[] { extensionFile });

                context.Display(logMessage, "text/markdown");

                var scriptContents = File.ReadAllText(extensionFile.FullName, Encoding.UTF8);
                await kernel.SubmitCodeAsync(scriptContents);
            }
        }
예제 #6
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;
            }
        }
예제 #7
0
        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.Display($"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(new KernelExtensionLoadException(e));
                    }
                }
            }
        }