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;
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[..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[(i + 1)..].Trim();
100 else
101 Title = null;
102
104 AsyncState State = new AsyncState()
105 {
106 Id = await asyncHtmlOutput.GenerateStub(MarkdownOutputType.Html, Renderer.Output, Title, Document),
107 Script = this.BuildExpression(Rows),
109 ImplicitPrint = new StringBuilder()
110 };
111
112 State.Variables.ConsoleOut = new StringWriter(State.ImplicitPrint);
113 Document.Settings.Variables?.CopyTo(State.Variables);
114
115 if (Document.Settings.Variables is SessionVariables CurrentSessionVariables)
116 {
117 SessionVariables.LastPost = CurrentSessionVariables.LastPost;
118 SessionVariables.CurrentRequest = CurrentSessionVariables.CurrentRequest;
119 SessionVariables.CurrentResponse = CurrentSessionVariables.CurrentResponse;
120 SessionVariables.CurrentPageVariables = CurrentSessionVariables.CurrentPageVariables;
121 SessionVariables.CurrentPageUrl = CurrentSessionVariables.CurrentPageUrl;
122 }
123
124 Document.QueueAsyncTask(this.ExecuteScript, State);
125
126 return true;
127 }
128
129 private class AsyncState
130 {
131 public string Id;
132 public Expression Script;
133 public Variables Variables;
134 public StringBuilder ImplicitPrint;
135 }
136
137 private Task ExecuteScript(object State)
138 {
139 AsyncState AsyncState = (AsyncState)State;
140 return this.Evaluate(AsyncState.Script, AsyncState.Variables, AsyncState.ImplicitPrint, AsyncState.Id);
141 }
142
143 private Expression BuildExpression(string[] Rows)
144 {
145 return new Expression(MarkdownDocument.AppendRows(Rows), this.document?.FileName);
146 }
147
148 private async Task<object> Evaluate(Expression Script, Variables Variables)
149 {
150 try
151 {
152 return await Script.EvaluateAsync(Variables);
153 }
154 catch (Exception ex)
155 {
156 return Log.UnnestException(ex);
157 }
158 }
159
160 private async Task Evaluate(Expression Script, Variables Variables, StringBuilder ImplicitPrint, string Id)
161 {
162 async Task Preview(object Sender, PreviewEventArgs e)
163 {
164 try
165 {
166 using HtmlRenderer Renderer2 = new HtmlRenderer(new HtmlSettings()
167 {
168 XmlEntitiesOnly = true
169 });
170
171 await Renderer2.RenderObject(e.Preview.AssociatedObjectValue, true, Variables);
172 await asyncHtmlOutput.ReportResult(MarkdownOutputType.Html, Id, Renderer2.ToString(), true);
173 }
174 catch (Exception ex)
175 {
176 Log.Exception(ex);
177 }
178 };
179
181 {
182 XmlEntitiesOnly = true
183 });
184
185 Variables.OnPreview += Preview;
186 try
187 {
188 object Result = await this.Evaluate(Script, Variables);
189
190 string Printed = ImplicitPrint.ToString();
191 if (!string.IsNullOrEmpty(Printed))
192 {
193 StringBuilder sb = new StringBuilder();
194 sb.AppendLine("BodyOnly: 1");
195
196 if (this.document?.Settings.AllowScriptTag ?? false)
197 sb.AppendLine("AllowScriptTag: 1");
198
199 sb.AppendLine();
200 sb.Append(Printed);
201
203
204 if (!(this.document is null))
205 Doc = await MarkdownDocument.CreateAsync(sb.ToString(), this.document.Settings);
207 v.ValueObject is MarkdownSettings Settings)
208 {
209 Doc = await MarkdownDocument.CreateAsync(sb.ToString(), Settings);
210 }
211 else
212 Doc = await MarkdownDocument.CreateAsync(sb.ToString());
213
214 await Doc.RenderDocument(Renderer);
215 }
216
217 await Renderer.RenderObject(Result, true, Variables);
218 }
219 catch (Exception ex)
220 {
221 Renderer.Clear();
222 await Renderer.RenderObject(ex, true, Variables);
223 }
224 finally
225 {
226 Variables.OnPreview -= Preview;
227 }
228
229 await asyncHtmlOutput.ReportResult(MarkdownOutputType.Html, Id, Renderer.ToString(), false);
230 }
231
241 public async Task<bool> RenderMarkdown(MarkdownRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
242 {
243 Expression Script = this.BuildExpression(Rows);
244 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
245 object Result = await this.Evaluate(Script, Variables);
246
247 await Renderer.RenderObject(Result, true, Variables);
248
249 return true;
250 }
251
261 public async Task<bool> RenderText(TextRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
262 {
263 Expression Script = this.BuildExpression(Rows);
264 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
265 object Result = await this.Evaluate(Script, Variables);
266
267 await Renderer.RenderObject(Result, true);
268
269 return true;
270 }
271
281 public async Task<bool> RenderWpfXaml(WpfXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
282 {
283 Expression Script = this.BuildExpression(Rows);
284 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
285 object Result = await this.Evaluate(Script, Variables);
286
287 await Renderer.RenderObject(Result, true, Variables);
288
289 return true;
290 }
291
301 public async Task<bool> RenderXamarinFormsXaml(XamarinFormsXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
302 {
303 Expression Script = this.BuildExpression(Rows);
304 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
305 object Result = await this.Evaluate(Script, Variables);
306
307 await Renderer.RenderObject(Result, true, Variables);
308
309 return true;
310 }
311
321 public async Task<bool> RenderLatex(LatexRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
322 {
323 Expression Script = this.BuildExpression(Rows);
324 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
325 object Result = await this.Evaluate(Script, Variables);
326
327 await Renderer.RenderObject(Result, true, Variables);
328
329 return true;
330 }
331
341 public async Task<bool> RenderContractXml(ContractsRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
342 {
343 Expression Script = this.BuildExpression(Rows);
344 Variables Variables = Document.Settings.Variables ?? HttpServer.CreateSessionVariables();
345 object Result = await this.Evaluate(Script, Variables);
346
347 await Renderer.RenderObject(Result, true, Variables);
348
349 return true;
350 }
351
352 }
353}
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:25
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:15
readonly StringBuilder Output
Renderer output.
Definition: Renderer.cs:19
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:18
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:14
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:1657
static Exception UnnestException(Exception Exception)
Unnests an exception, to extract the relevant inner exception.
Definition: Log.cs:828
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:321
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:301
async Task< bool > RenderMarkdown(MarkdownRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates Markdown for the code content.
Definition: AsyncScript.cs:241
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:341
async Task< bool > RenderWpfXaml(WpfXamlRenderer Renderer, string[] Rows, string Language, int Indent, MarkdownDocument Document)
Generates WPF XAML for the code content.
Definition: AsyncScript.cs:281
AsyncScript()
Class managing asynchronous script execution in 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:261
Implements an HTTP server.
Definition: HttpServer.cs:41
static SessionVariables CreateSessionVariables()
Creates a new collection of variables, that contains access to the global set of variables.
Definition: HttpServer.cs:2130
Collection of session variables.
Class managing a script expression.
Definition: Expression.cs:41
async Task< object > EvaluateAsync(Variables Variables)
Evaluates the expression, using the variables provided in the Variables collection....
Definition: Expression.cs:4461
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:334
virtual bool TryGetVariable(string Name, out Variable Variable)
Tries to get a variable object, given its name.
Definition: Variables.cs:56
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