Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
AsyncScript.cs
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Text;
5using System.Threading.Tasks;
13using Waher.Events;
16using Waher.Script;
17
19{
25 {
26 private static readonly AsyncMarkdownHtmlContent asyncHtmlOutput = new AsyncMarkdownHtmlContent();
27
28 private MarkdownDocument document;
29
33 public AsyncScript()
34 {
35 }
36
42 public Grade Supports(string Language)
43 {
44 int i = Language.IndexOf(':');
45 if (i > 0)
46 Language = Language.Substring(0, i).TrimEnd();
47
48 if (string.Compare(Language, "async", true) == 0)
49 return Grade.Excellent;
50 else
51 return Grade.NotAtAll;
52 }
53
57 public bool EvaluatesScript => true;
58
63 public void Register(MarkdownDocument Document)
64 {
65 this.document = Document;
66
67 if (!Document.TryGetMetaData("JAVASCRIPT", out KeyValuePair<string, bool>[] Values) ||
68 !Contains(Values, "/Events.js"))
69 {
70 Document.AddMetaData("JAVASCRIPT", "/Events.js");
71 }
72 }
73
74 private static bool Contains(KeyValuePair<string, bool>[] Values, string Value)
75 {
76 foreach (KeyValuePair<string, bool> P in Values)
77 {
78 if (string.Compare(P.Key, Value, true) == 0)
79 return true;
80 }
81
82 return false;
83 }
84
94 public async Task<bool> RenderHtml(HtmlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
95 {
96 string Title;
97 int i = Language.IndexOf(':');
98 if (i > 0)
99 Title = Language.Substring(i + 1).Trim();
100 else
101 Title = null;
102
103 AsyncState State = new AsyncState()
104 {
105 Id = await asyncHtmlOutput.GenerateStub(MarkdownOutputType.Html, Renderer.Output, Title, Document),
106 Script = this.BuildExpression(Rows),
108 ImplicitPrint = new StringBuilder()
109 };
110
111 State.Variables.ConsoleOut = new StringWriter(State.ImplicitPrint);
112 Document.Settings.Variables?.CopyTo(State.Variables);
113
114 Document.QueueAsyncTask(this.ExecuteScript, State);
115
116 return true;
117 }
118
119 private class AsyncState
120 {
121 public string Id;
122 public Expression Script;
123 public Variables Variables;
124 public StringBuilder ImplicitPrint;
125 }
126
127 private Task ExecuteScript(object State)
128 {
129 AsyncState AsyncState = (AsyncState)State;
130 return this.Evaluate(AsyncState.Script, AsyncState.Variables, AsyncState.ImplicitPrint, AsyncState.Id);
131 }
132
133 private Expression BuildExpression(string[] Rows)
134 {
135 return new Expression(MarkdownDocument.AppendRows(Rows), this.document?.FileName);
136 }
137
138 private async Task<object> Evaluate(Expression Script, Variables Variables)
139 {
140 try
141 {
142 return await Script.EvaluateAsync(Variables);
143 }
144 catch (Exception ex)
145 {
146 return Log.UnnestException(ex);
147 }
148 }
149
150 private async Task Evaluate(Expression Script, Variables Variables, StringBuilder ImplicitPrint, string Id)
151 {
152 async Task Preview(object Sender, PreviewEventArgs e)
153 {
154 try
155 {
156 using (HtmlRenderer Renderer2 = new HtmlRenderer(new HtmlSettings()
157 {
158 XmlEntitiesOnly = true
159 }))
160 {
161 await Renderer2.RenderObject(e.Preview.AssociatedObjectValue, true, Variables);
162 await asyncHtmlOutput.ReportResult(MarkdownOutputType.Html, Id, Renderer2.ToString(), true);
163 }
164 }
165 catch (Exception ex)
166 {
167 Log.Exception(ex);
168 }
169 };
170
172 {
173 XmlEntitiesOnly = true
174 }))
175 {
176 Variables.OnPreview += Preview;
177 try
178 {
179 object Result = await this.Evaluate(Script, Variables);
180
181 string Printed = ImplicitPrint.ToString();
182 if (!string.IsNullOrEmpty(Printed))
183 {
184 StringBuilder sb = new StringBuilder();
185 sb.AppendLine("BodyOnly: 1");
186
187 if (this.document?.Settings.AllowScriptTag ?? false)
188 sb.AppendLine("AllowScriptTag: 1");
189
190 sb.AppendLine();
191 sb.Append(Printed);
192
194
195 if (!(this.document is null))
196 Doc = await MarkdownDocument.CreateAsync(sb.ToString(), this.document.Settings);
198 v.ValueObject is MarkdownSettings Settings)
199 {
200 Doc = await MarkdownDocument.CreateAsync(sb.ToString(), Settings);
201 }
202 else
203 Doc = await MarkdownDocument.CreateAsync(sb.ToString());
204
205 await Doc.RenderDocument(Renderer);
206 }
207
208 await Renderer.RenderObject(Result, true, Variables);
209 }
210 catch (Exception ex)
211 {
212 Renderer.Clear();
213 await Renderer.RenderObject(ex, true, Variables);
214 }
215 finally
216 {
217 Variables.OnPreview -= Preview;
218 }
219
220 await asyncHtmlOutput.ReportResult(MarkdownOutputType.Html, Id, Renderer.ToString(), false);
221 }
222 }
223
233 public async Task<bool> RenderMarkdown(MarkdownRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
234 {
235 Expression Script = this.BuildExpression(Rows);
236 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
237 object Result = await this.Evaluate(Script, Variables);
238
239 await Renderer.RenderObject(Result, true, Variables);
240
241 return true;
242 }
243
253 public async Task<bool> RenderText(TextRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
254 {
255 Expression Script = this.BuildExpression(Rows);
256 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
257 object Result = await this.Evaluate(Script, Variables);
258
259 await Renderer.RenderObject(Result, true);
260
261 return true;
262 }
263
273 public async Task<bool> RenderWpfXaml(WpfXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
274 {
275 Expression Script = this.BuildExpression(Rows);
276 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
277 object Result = await this.Evaluate(Script, Variables);
278
279 await Renderer.RenderObject(Result, true, Variables);
280
281 return true;
282 }
283
293 public async Task<bool> RenderXamarinFormsXaml(XamarinFormsXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
294 {
295 Expression Script = this.BuildExpression(Rows);
296 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
297 object Result = await this.Evaluate(Script, Variables);
298
299 await Renderer.RenderObject(Result, true, Variables);
300
301 return true;
302 }
303
313 public async Task<bool> RenderLatex(LatexRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
314 {
315 Expression Script = this.BuildExpression(Rows);
316 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
317 object Result = await this.Evaluate(Script, Variables);
318
319 await Renderer.RenderObject(Result, true, Variables);
320
321 return true;
322 }
323
333 public async Task<bool> RenderContractXml(ContractsRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
334 {
335 Expression Script = this.BuildExpression(Rows);
336 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateVariables();
337 object Result = await this.Evaluate(Script, Variables);
338
339 await Renderer.RenderObject(Result, true, Variables);
340
341 return true;
342 }
343
344 }
345}
Renders Contracts XML from a Markdown document.
Renders LaTeX from a Markdown document.
Contains a markdown document. This markdown document class supports original markdown,...
static string AppendRows(string[] Rows)
Appends a set of rows into a single string with newlines between rows.
MarkdownSettings Settings
Markdown settings.
async Task RenderDocument(IRenderer Output)
Renders the document using provided output format.
bool AllowScriptTag
If client-side script tags are allowed in the document.
void QueueAsyncTask(AsyncMarkdownProcessing Callback, object State)
Queues an asynchronous task to be executed. Asynchronous tasks will be executed after the main docume...
bool TryGetMetaData(string Key, out KeyValuePair< string, bool >[] Value)
Tries to get a meta-data value given its key.
void AddMetaData(string Key, string Value)
Adds meta-data to the document.
const string MarkdownSettingsVariableName
Variable name used for storing Markdown settings.
static Task< MarkdownDocument > CreateAsync(string MarkdownText, params Type[] TransparentExceptionTypes)
Contains a markdown document. This markdown document class supports original markdown,...
Contains settings that the Markdown parser uses to customize its behavior.
Variables Variables
Collection of variables. Providing such a collection enables script execution inside markdown documen...
Renders HTML from a Markdown document.
Definition: HtmlRenderer.cs:24
async Task RenderObject(object Result, bool AloneInParagraph, Variables Variables)
Generates HTML from Script output.
Contains settings that the HTML export uses to customize HTML output.
Definition: HtmlSettings.cs:7
Renders portable Markdown from a Markdown document.
Abstract base class for Markdown renderers.
Definition: Renderer.cs:14
readonly StringBuilder Output
Renderer output.
Definition: Renderer.cs:18
void Clear()
Clears the underlying StringBuilder.
Definition: Renderer.cs:138
override string ToString()
Returns the renderer output.
Definition: Renderer.cs:130
Renders plain text from a Markdown document.
Definition: TextRenderer.cs:16
Renders XAML (WPF flavour) from a Markdown document.
Renders XAML (Xamarin.Forms flavour) from a Markdown document.
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
Definition: Log.cs:1647
static Exception UnnestException(Exception Exception)
Unnests an exception, to extract the relevant inner exception.
Definition: Log.cs:818
Pushes asynchronously generated HTML content to clients
Class managing asynchronous script execution in Markdown documents.
Definition: AsyncScript.cs:25
bool EvaluatesScript
If script is evaluated for this type of code block.
Definition: AsyncScript.cs:57
Grade Supports(string Language)
Checks how well the handler supports multimedia content of a given type.
Definition: AsyncScript.cs:42
async Task< bool > RenderLatex(LatexRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates LaTeX for the code content.
Definition: AsyncScript.cs:313
async Task< bool > RenderXamarinFormsXaml(XamarinFormsXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates Xamarin.Forms XAML for the code content.
Definition: AsyncScript.cs:293
async Task< bool > RenderMarkdown(MarkdownRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates Markdown for the code content.
Definition: AsyncScript.cs:233
async Task< bool > RenderContractXml(ContractsRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates smart contract XML for the code content.
Definition: AsyncScript.cs:333
async Task< bool > RenderWpfXaml(WpfXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates WPF XAML for the code content.
Definition: AsyncScript.cs:273
AsyncScript()
Class managing 2D XML Layout integration into Markdown documents.
Definition: AsyncScript.cs:33
async Task< bool > RenderHtml(HtmlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates HTML for the code content.
Definition: AsyncScript.cs:94
void Register(MarkdownDocument Document)
Is called on the object when an instance of the element has been created in a document.
Definition: AsyncScript.cs:63
async Task< bool > RenderText(TextRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates plain text for the code content.
Definition: AsyncScript.cs:253
Implements an HTTP server.
Definition: HttpServer.cs:36
static Variables CreateVariables()
Creates a new collection of variables, that contains access to the global set of variables.
Definition: HttpServer.cs:1604
Class managing a script expression.
Definition: Expression.cs:39
async Task< object > EvaluateAsync(Variables Variables)
Evaluates the expression, using the variables provided in the Variables collection....
Definition: Expression.cs:4275
Event arguments for preview events.
IElement Preview
Preview of result.
Contains information about a variable.
Definition: Variable.cs:10
Collection of variables.
Definition: Variables.cs:25
void CopyTo(Variables Variables)
Copies available variables to another variable collection.
Definition: Variables.cs:400
virtual bool TryGetVariable(string Name, out Variable Variable)
Tries to get a variable object, given its name.
Definition: Variables.cs:52
Interface for all markdown handlers of code content.
Definition: ICodeContent.cs:9
Interface for code content plain text renderers.
Interface for code content WPF XAML renderers.
MarkdownOutputType
Markdown output type.
Grade
Grade enumeration
Definition: Grade.cs:7