private void OnCommandHandled(IJupyterMessageSender jupyterMessageSender)
        {
            // reply ok
            var executeReplyPayload = new ExecuteReplyOk(executionCount: _executionCount);

            // send to server
            jupyterMessageSender.Send(executeReplyPayload);
        }
예제 #2
0
        public async void Process(Message <T> message)
        {
            object result = null;

            try
            {
                var displayDataHandler = new Action <DisplayData>((data) =>
                {
                    _ioPub.Send(message, data, MessageType.DisplayData);
                });

                DisplayDataEmitter.DisplayDataHandler = displayDataHandler;

                using (var consoleProxy = CreateConsoleProxy(displayDataHandler))
                {
                    consoleProxy.StartRedirect();
                    result = await _scriptEngine.ExecuteAsync(message.Content.Code);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to run the code: " + message.Content.Code);

                var error = e.Message + Environment.NewLine + e.StackTrace;
                _ioPub.Send(message, new DisplayData(error, $"<p style=\"color:red;\">{error}</p>"), MessageType.DisplayData);
                return;
            }
            finally
            {
                DisplayDataEmitter.DisplayDataHandler = null;
            }

            if (result == null)
            {
                return;
            }

            _ioPub.Send(message, result, MessageType.DisplayData);

            // send execute reply to shell socket
            var executeReply = new ExecuteReplyOk
            {
                ExecutionCount  = _executionCount++,
                Payload         = new List <Dictionary <string, string> >(),
                UserExpressions = new Dictionary <string, string>()
            };

            _shell.Send(message, executeReply, MessageType.ExecuteReply);
        }
예제 #3
0
        private void OnCommandHandled(
            CommandHandled commandHandled,
            Message request,
            IMessageSender serverChannel)
        {
            // reply ok
            var executeReplyPayload = new ExecuteReplyOk(executionCount: _executionCount);

            // send to server
            var executeReply = Message.CreateResponse(
                executeReplyPayload,
                request);

            serverChannel.Send(executeReply);
        }
예제 #4
0
        public void SendExecuteReplyMessage(Message message, RouterSocket shellSocket)
        {
            ExecuteReplyOk executeReply = new ExecuteReplyOk()
            {
                ExecutionCount  = this.executionCount,
                Payload         = new List <Dictionary <string, string> >(),
                UserExpressions = new Dictionary <string, string>()
            };

            Message executeReplyMessage = MessageBuilder.CreateMessage(MessageTypeValues.ExecuteReply,
                                                                       JsonSerializer.Serialize(executeReply), message.Header);

            this.logger.Info(string.Format("Sending message to Shell {0}", JsonSerializer.Serialize(executeReplyMessage)));
            MessageSender.Send(executeReplyMessage, shellSocket);
        }
예제 #5
0
        private static void OnCodeSubmissionEvaluated(CodeSubmissionEvaluated codeSubmissionEvaluated,
                                                      ConcurrentDictionary <Guid, OpenRequest> openRequests)
        {
            var openRequest = openRequests[codeSubmissionEvaluated.ParentId];
            // reply ok
            var executeReplyPayload = new ExecuteReplyOk(executionCount: openRequest.ExecutionCount);

            // send to server
            var executeReply = Message.CreateResponse(
                executeReplyPayload,
                openRequest.Context.Request);

            openRequest.Context.ServerChannel.Send(executeReply);
            openRequest.Context.RequestHandlerStatus.SetAsIdle();
        }
예제 #6
0
        private static void OnCodeSubmissionEvaluated(CodeSubmissionEvaluated codeSubmissionEvaluated,
                                                      ConcurrentDictionary <IKernelCommand, InflightRequest> openRequests)
        {
            openRequests.TryRemove(codeSubmissionEvaluated.Command, out var openRequest);
            // reply ok
            var executeReplyPayload = new ExecuteReplyOk(executionCount: openRequest.ExecutionCount);

            // send to server
            var executeReply = Message.CreateResponse(
                executeReplyPayload,
                openRequest.Context.Request);

            openRequest.Context.ServerChannel.Send(executeReply);
            openRequest.Context.RequestHandlerStatus.SetAsIdle();
            openRequest.Dispose();
        }
예제 #7
0
        public void SendExecuteReplyOkMessage(Message message, RouterSocket shellSocket)
        {
            ExecuteReplyOk executeReply = new ExecuteReplyOk()
            {
                ExecutionCount  = this.executionCount,
                Payload         = new List <Dictionary <string, string> >(),
                UserExpressions = new Dictionary <string, string>()
            };

            Message executeReplyMessage = MessageBuilder.CreateMessage(MessageTypeValues.ExecuteReply, JObject.FromObject(executeReply), message.Header);

            // Stick the original identifiers on the message so they'll be sent first
            // Necessary since the shell socket is a ROUTER socket
            executeReplyMessage.Identifiers = message.Identifiers;

            this.logger.Info(string.Format("Sending message to Shell {0}", JsonSerializer.Serialize(executeReplyMessage)));
            this.messageSender.Send(executeReplyMessage, shellSocket);
        }
예제 #8
0
        private void OnCommandHandled(CommandHandled commandHandled)
        {
            if (!InFlightRequests.TryRemove(commandHandled.GetRootCommand(), out var openRequest))
            {
                return;
            }

            // reply ok
            var executeReplyPayload = new ExecuteReplyOk(executionCount: openRequest.ExecutionCount);

            // send to server
            var executeReply = Message.CreateResponse(
                executeReplyPayload,
                openRequest.Context.Request);

            openRequest.Context.ServerChannel.Send(executeReply);
            openRequest.Context.RequestHandlerStatus.SetAsIdle();
            openRequest.Dispose();
        }
예제 #9
0
        public async Task <ICommandDeliveryResult> Handle(
            ICommandDelivery <JupyterRequestContext> delivery)
        {
            switch (delivery.Command.Request.Header.MessageType)
            {
            case MessageTypeValues.ExecuteRequest:
                var transient = new Dictionary <string, object> {
                    { "display_id", Guid.NewGuid().ToString() }
                };

                var jObject        = (JObject)delivery.Command.Request.Content;
                var executeRequest = jObject.ToObject <ExecuteRequest>();

                var code = executeRequest.Code;

                var workspace = new Workspace(
                    files: new[]
                {
                    new File("Program.cs", Scaffold())
                },
                    buffers: new[]
                {
                    new Buffer(new BufferId("Program.cs", "main"), code),
                },
                    workspaceType: "console");

                var workspaceRequest = new WorkspaceRequest(workspace);

                var server = new WorkspaceServerMultiplexer(new PackageRegistry());

                var result = await server.Run(workspaceRequest);

                var messageBuilder = delivery.Command.Builder;
                var ioPubChannel   = delivery.Command.IoPubChannel;
                var serverChannel  = delivery.Command.ServerChannel;

                if (!executeRequest.Silent)
                {
                    _executionCount++;

                    var executeInput = messageBuilder.CreateMessage(
                        MessageTypeValues.ExecuteInput,
                        new ExecuteInput
                    {
                        Code           = code,
                        ExecutionCount = _executionCount
                    },
                        delivery.Command.Request.Header);

                    ioPubChannel.Send(executeInput);
                }

                // execute result
                var output = string.Join("\n", result.Output);


                // executeResult data
                var executeResultData = new ExecuteResult()
                {
                    Data = new JObject
                    {
                        { "text/html", output },
                        { "text/plain", output }
                    },
                    Transient      = transient,
                    ExecutionCount = _executionCount
                };



                var resultSucceeded = result.Succeeded &&
                                      result.Exception == null;

                if (resultSucceeded)
                {
                    // reply ok
                    var executeReplyPayload = new ExecuteReplyOk
                    {
                        ExecutionCount = _executionCount
                    };

                    // send to server
                    var executeReply = messageBuilder.CreateMessage(
                        MessageTypeValues.ExecuteReply,
                        executeReplyPayload,
                        delivery.Command.Request.Header);

                    executeReply.Identifiers = delivery.Command.Request.Identifiers;

                    serverChannel.Send(executeReply);
                }
                else
                {
                    var errorContent = new Error
                    {
                        EName = string.IsNullOrWhiteSpace(result.Exception)
                                        ? "Compile Error"
                                        : "Unhandled Exception",
                        EValue    = output,
                        Traceback = new List <string>()
                    };

                    //  reply Error
                    var executeReplyPayload = new ExecuteReplyError(errorContent)
                    {
                        ExecutionCount = _executionCount
                    };

                    // send to server
                    var executeReply = messageBuilder.CreateMessage(
                        MessageTypeValues.ExecuteReply,
                        executeReplyPayload,
                        delivery.Command.Request.Header);

                    executeReply.Identifiers = delivery.Command.Request.Identifiers;

                    serverChannel.Send(executeReply);

                    if (!executeRequest.Silent)
                    {
                        // send on io
                        var error = messageBuilder.CreateMessage(
                            MessageTypeValues.Error,
                            errorContent,
                            delivery.Command.Request.Header);
                        ioPubChannel.Send(error);

                        // send on stderr
                        var stdErr = new StdErrStream
                        {
                            Text = errorContent.EValue
                        };
                        var stream = messageBuilder.CreateMessage(
                            MessageTypeValues.Stream,
                            stdErr,
                            delivery.Command.Request.Header);
                        ioPubChannel.Send(stream);
                    }
                }

                if (!executeRequest.Silent && resultSucceeded)
                {
                    // send on io
                    var executeResultMessage = messageBuilder.CreateMessage(
                        MessageTypeValues.ExecuteResult,
                        executeResultData,
                        delivery.Command.Request.Header);
                    ioPubChannel.Send(executeResultMessage);
                }

                break;
            }

            return(delivery.Complete());
        }
        private async Task HandleExecuteRequest(ICommandDelivery <JupyterRequestContext> delivery)
        {
            var ioPubChannel  = delivery.Command.IoPubChannel;
            var serverChannel = delivery.Command.ServerChannel;

            var transient = new Dictionary <string, object> {
                { "display_id", Guid.NewGuid().ToString() }
            };

            var executeRequest = delivery.Command.GetRequestContent <ExecuteRequest>();

            var code = executeRequest.Code;

            var workspace = CreateScaffoldWorkspace(code);

            var workspaceRequest = new WorkspaceRequest(workspace);

            var result = await _server.Run(workspaceRequest);

            if (!executeRequest.Silent)
            {
                _executionCount++;

                var executeInput = Message.Create(
                    new ExecuteInput(code: code, executionCount: _executionCount),
                    delivery.Command.Request.Header);

                ioPubChannel.Send(executeInput);
            }

            // execute result
            var output = string.Join("\n", result.Output);


            // executeResult data
            var executeResultData = new ExecuteResult(
                _executionCount,
                transient: transient,
                data: new Dictionary <string, object> {
                { "text/html", output },
                { "text/plain", output }
            });


            var resultSucceeded = result.Succeeded &&
                                  result.Exception == null;

            if (resultSucceeded)
            {
                // reply ok
                var executeReplyPayload = new ExecuteReplyOk(executionCount: _executionCount);


                // send to server
                var executeReply = Message.CreateResponse(
                    executeReplyPayload,
                    delivery.Command.Request);

                serverChannel.Send(executeReply);
            }
            else
            {
                var errorContent = new Error(
                    eName: string.IsNullOrWhiteSpace(result.Exception) ? "Compile Error" : "Unhandled Exception",
                    eValue: output
                    );

                //  reply Error
                var executeReplyPayload = new ExecuteReplyError(errorContent, executionCount: _executionCount);

                // send to server
                var executeReply = Message.CreateResponse(
                    executeReplyPayload,
                    delivery.Command.Request);

                serverChannel.Send(executeReply);

                if (!executeRequest.Silent)
                {
                    // send on io
                    var error = Message.Create(
                        errorContent,
                        delivery.Command.Request.Header);
                    ioPubChannel.Send(error);

                    // send on stderr
                    var stdErr = new StdErrStream(errorContent.EValue);
                    var stream = Message.Create(
                        stdErr,
                        delivery.Command.Request.Header);
                    ioPubChannel.Send(stream);
                }
            }

            if (!executeRequest.Silent && resultSucceeded)
            {
                // send on io
                var executeResultMessage = Message.Create(
                    executeResultData,
                    delivery.Command.Request.Header);
                ioPubChannel.Send(executeResultMessage);
            }
        }
예제 #11
0
        internal void executeRequest(KernelMessage msg, ExecuteRequest content)
        {
            Evaluation.sbOut.Clear();
            Evaluation.sbErr.Clear();
            Evaluation.sbPrint.Clear();
            payload.Clear();

            if (!content.silent)
            {
                executionCount++;
            }

            // sending busy
            sendStateBusy(msg);
            sendMessage(ioSocket, msg, "pyin", new Pyin()
            {
                code = content.code, execution_count = executionCount
            });

            // preprocess
            var newCode = preprocessCode(content.code);

            if (!String.IsNullOrEmpty(newCode))
            {
                // evaluate
                try
                {
                    (var value, var errors) = Evaluation.EvalInteractionNonThrowing(newCode);

                    if (errors.Length > 0)
                    {
                        var sb = errors.Aggregate(new StringBuilder(), (ag, n) => ag.AppendLine(n));
                        sendError(sb.ToString(), msg);
                    }
                    var executeReply = new ExecuteReplyOk()
                    {
                        status           = "ok",
                        execution_count  = executionCount,
                        payload          = payload.ToArray(),
                        user_variables   = new Dictionary <string, object>(),
                        user_expressions = new Dictionary <string, object>()
                    };

                    sendMessage(shellSocket, msg, "execute_reply", executeReply);

                    // send all the data
                    if (!content.silent)
                    {
                        var lastExpression = Evaluation.GetLastExpression();

                        if (lastExpression != null)
                        {
                            var printedResult = Printers.PrintVariable(lastExpression);
                            sendDisplayData(printedResult.ContentType, printedResult.Data, "pyout");
                        }
                    }
                }
                catch (AggregateException ae)
                {
                    var esb = new StringBuilder();
                    esb.AppendLine(ae.Message);

                    foreach (var e in ae.InnerExceptions)
                    {
                        esb.AppendLine(e.Message);
                    }

                    sendError(esb.ToString(), msg);
                }
                catch (Exception ex)
                {
                    var error = $"Expression evaluation failed: {ex.Message}\r\n {ex.StackTrace}";
                    sendError(error, msg);
                }
            }

            if (Evaluation.sbPrint.Length > 0)
            {
                sendDisplayData("text/plain", Evaluation.sbPrint.ToString(), "display_data");
            }

            sendStateIdle(msg);
        }