/
MicrosoftXsltEngine.cs
436 lines (407 loc) · 19.9 KB
/
MicrosoftXsltEngine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#region license
/*
Copyright 2005 - 2021 Advantage Solutions, s. r. o.
This file is part of ORIGAM (http://www.origam.org).
ORIGAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ORIGAM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ORIGAM. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Mvp.Xml.Exslt;
using Origam.DA.ObjectPersistence;
using Origam.Rule.XsltFunctions;
using Origam.Schema.EntityModel;
using Origam.Service.Core;
namespace Origam.Rule.Xslt
{
public abstract class MicrosoftXsltEngine : AbstractXsltEngine
{
private readonly IEnumerable<XsltFunctionsDefinition> functionsDefinitions;
#region Constructors
protected MicrosoftXsltEngine()
{
functionsDefinitions = XsltFunctionContainerFactory.Create();
}
public MicrosoftXsltEngine(IEnumerable<XsltFunctionsDefinition> functionsDefinitions) : base ()
{
this.functionsDefinitions = functionsDefinitions ?? XsltFunctionContainerFactory.Create();
}
public MicrosoftXsltEngine(IPersistenceProvider persistence)
: base(persistence)
{
functionsDefinitions = XsltFunctionContainerFactory.Create();
}
#endregion
internal override IXmlContainer Transform(IXmlContainer data, object xsltEngine,
Hashtable parameters, string transactionId,
IDataStructure outputStructure, bool validateOnly)
{
XsltArgumentList xslArg = BuildArgumentListWithFunctions(transactionId);
// If source xml is completely empty (not even a root element), we add one
// with a name of dataset.datasetname (that's how root element looks like when
// data come from a dataset.
// It does not do anything with a non-dataset xml source.
IDataDocument dataDocument = data as IDataDocument;
if (data.Xml.DocumentElement == null && dataDocument !=null)
{
bool oldEnforceConstraints = dataDocument.DataSet.EnforceConstraints;
dataDocument.DataSet.EnforceConstraints = false;
dataDocument.AppendChild(XmlNodeType.Element,
dataDocument.DataSet.DataSetName, "");
dataDocument.DataSet.EnforceConstraints = oldEnforceConstraints;
}
IXmlContainer resultDoc;
// Generate empty dataset of output structure
if (outputStructure is DataStructure)
{
DataSet result = this.GetEmptyData(outputStructure.PrimaryKey);
// result dataset will not have enabled constraints, because it can load fragments
// constraints will be checked after merging into original context
result.EnforceConstraints = false;
resultDoc = DataDocumentFactory.New(result);
}
else if (outputStructure == null | outputStructure is XsdDataStructure)
{
resultDoc = new XmlContainer();
}
else throw new InvalidOperationException(ResourceUtils.GetString("ErrorTransformationSupport"));
try
{
StringBuilder traceParameters = new StringBuilder();
// Parameters
if (parameters != null)
{
foreach (DictionaryEntry param in parameters)
{
object val = param.Value;
if (param.Value is IXmlContainer xmlContainer)
{
XPathDocument paramXpathDoc = new XPathDocument(
new XmlNodeReader(xmlContainer.Xml));
XPathNavigator nav = paramXpathDoc.CreateNavigator();
XPathNodeIterator iterator = nav.Select("/");
val = iterator;
}
else if (param.Value is bool)
{
val = param.Value;
}
else
{
val = XmlTools.ConvertToString(param.Value);
}
if (val != null)
{
xslArg.AddParam(param.Key.ToString(), "", val);
}
if (this.Trace)
{
string traceValue;
if (param.Value is IXmlContainer traceXmlContainer)
{
StringBuilder sb = new StringBuilder();
sb.Append("AS:ToXml('");
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = new XmlTextWriter(sw);
traceXmlContainer.Xml.Save(xtw);
sb.Append("')");
traceValue = sb.ToString();
if (traceValue == "AS:ToXml('')")
{
traceValue = "";
}
}
else if (val == null)
{
traceValue = "";
}
else
{
traceValue = XmlTools.ConvertToString(val);
}
if (traceParameters.Length > 0) traceParameters.Append(Environment.NewLine);
if (traceValue == "")
{
traceParameters.AppendFormat("<xsl:param name=\"{0}\" />",
param.Key.ToString());
}
else
{
traceParameters.AppendFormat("<xsl:param name=\"{0}\" select=\"{1}\"/>",
param.Key.ToString(), traceValue);
}
}
}
}
if (this.Trace)
{
StringBuilder b = new StringBuilder();
StringWriter swr = new StringWriter(b);
XmlTextWriter xwr = new XmlTextWriter(swr);
xwr.Formatting = Formatting.Indented;
data.Xml.WriteTo(xwr);
xwr.Close();
swr.Close();
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName, this.TraceStepId, "Transformation Service", "Input", null, b.ToString(), traceParameters.ToString(), null);
}
XPathDocument sourceXpathDoc = new XPathDocument(new XmlNodeReader(data.Xml));
try
{
if (this.Trace && resultDoc is IDataDocument)
{
IXmlContainer traceDocument = new XmlContainer();
// first transform to a temporary xml document so we see the clean transformation output
Transform(xsltEngine, xslArg, sourceXpathDoc, traceDocument);
// trace
TraceResult(traceDocument);
// after writing the trace we will load the results into the final dataset
resultDoc.Load(new XmlNodeReader(traceDocument.Xml));
}
else
{
// without tracing we transform directly to the target dataset
Transform(xsltEngine, xslArg, sourceXpathDoc, resultDoc);
if (this.Trace)
{
TraceResult(resultDoc);
}
}
}
catch (XsltException ex)
{
string terminateStringEnglish = "Transform terminated:";
string terminateString = ResourceUtils.GetString("XsltTransformTerminated");
if (ex.Message.Length >= terminateString.Length &&
ex.Message.Substring(0, terminateString.Length) == terminateString)
{
throw new OrigamRuleException(ex.Message.Substring(terminateString.Length + 1, ex.Message.Length - 2 - terminateString.Length), ex, null);
}
else if (ex.Message.Length >= terminateStringEnglish.Length &&
ex.Message.Substring(0, terminateStringEnglish.Length) == terminateStringEnglish)
{
throw new OrigamRuleException(ex.Message.Substring(terminateStringEnglish.Length + 1, ex.Message.Length - 2 - terminateStringEnglish.Length), ex, null);
}
else
{
throw new Exception(ResourceUtils.GetString("ErrorResultInvalid"), ex);
}
}
catch (OrigamRuleException)
{
throw;
}
catch (Exception ex)
{
throw new Exception(ResourceUtils.GetString("ErrorResultInvalid"), ex);
}
}
catch (OrigamRuleException ex)
{
if (this.Trace)
{
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName, this.TraceStepId, "Transformation Service", "Error", null, null, null, ex.Message);
}
throw;
}
catch (Exception ex)
{
if (this.Trace)
{
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName, this.TraceStepId, "Transformation Service", "Error", null, null, null, ex.Message);
}
string innerMessage = (ex.InnerException == null ? ex.Message : (ex.InnerException.InnerException == null ? ex.InnerException.Message : (ex.InnerException.InnerException.InnerException == null ? ex.InnerException.InnerException.Message : ex.InnerException.InnerException.InnerException.Message)));
throw new Exception(innerMessage, ex);
}
return resultDoc;
}
internal override void Transform(
IXPathNavigable input, object xsltEngine, Hashtable parameters,
string transactionId, Stream output)
{
XsltArgumentList xslArg = BuildArgumentListWithFunctions(transactionId);
try
{
StringBuilder traceParameters = new StringBuilder();
if(parameters != null)
{
foreach(DictionaryEntry param in parameters)
{
object val = param.Value;
if(param.Value is byte[])
{
val = Convert.ToBase64String((byte[])param.Value);
}
else if(param.Value is DateTime)
{
val = XmlConvert.ToString((DateTime)param.Value);
}
else if(param.Value is XmlDocument)
{
XPathDocument paramXpathDoc = new XPathDocument(
new XmlNodeReader(param.Value as XmlDocument));
XPathNavigator nav = paramXpathDoc.CreateNavigator();
XPathNodeIterator iterator = nav.Select("/");
val = iterator;
}
if(val != null)
{
//throw new NullReferenceException("Transformation input parameter '" + param.Key.ToString() + "' cannot be null.");
xslArg.AddParam(param.Key.ToString(), "", val);
}
if(this.Trace)
{
string traceValue;
if(param.Value is XmlDocument)
{
XmlDocument xmlDoc = param.Value as XmlDocument;
StringBuilder sb = new StringBuilder();
sb.Append("AS:ToXml('");
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = new XmlTextWriter(sw);
xmlDoc.Save(xtw);
sb.Append("')");
traceValue = sb.ToString();
if(traceValue == "AS:ToXml('')")
{
traceValue = "";
}
}
else if(val == null)
{
traceValue = "";
}
else
{
traceValue = XmlTools.ConvertToString(val);
}
if(traceParameters.Length > 0)
{
traceParameters.Append(Environment.NewLine);
}
if(traceValue == "")
{
traceParameters.AppendFormat("<xsl:param name=\"{0}\" />",
param.Key.ToString());
}
else
{
traceParameters.AppendFormat("<xsl:param name=\"{0}\" select=\"{1}\"/>",
param.Key.ToString(), traceValue);
}
}
}
}
try
{
Transform(xsltEngine, xslArg, input, output);
}
catch(XsltException ex)
{
string terminateStringEnglish = "Transform terminated:";
string terminateString = ResourceUtils.GetString("XsltTransformTerminated");
if(ex.Message.Length >= terminateString.Length &&
ex.Message.Substring(0, terminateString.Length) == terminateString)
{
throw new OrigamRuleException(ex.Message.Substring(terminateString.Length + 1, ex.Message.Length - 2 - terminateString.Length), ex, null);
}
else if(ex.Message.Length >= terminateStringEnglish.Length &&
ex.Message.Substring(0, terminateStringEnglish.Length) == terminateStringEnglish)
{
throw new OrigamRuleException(ex.Message.Substring(terminateStringEnglish.Length + 1, ex.Message.Length - 2 - terminateStringEnglish.Length), ex, null);
}
else
{
throw new Exception(ResourceUtils.GetString("ErrorResultInvalid"), ex);
}
}
catch(OrigamRuleException)
{
throw;
}
catch(Exception ex)
{
throw new Exception(ResourceUtils.GetString("ErrorResultInvalid"), ex);
}
}
catch(OrigamRuleException ex)
{
if(this.Trace)
{
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName, this.TraceStepId, "Transformation Service", "Error", null, null, null, ex.Message);
}
throw;
}
catch(Exception ex)
{
if(this.Trace)
{
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName, this.TraceStepId, "Transformation Service", "Error", null, null, null, ex.Message);
}
string innerMessage = (ex.InnerException == null ? ex.Message : (ex.InnerException.InnerException == null ? ex.InnerException.Message : (ex.InnerException.InnerException.InnerException == null ? ex.InnerException.InnerException.Message : ex.InnerException.InnerException.InnerException.Message)));
throw new Exception(innerMessage, ex);
}
}
private XsltArgumentList BuildArgumentListWithFunctions(string transactionId)
{
XsltArgumentList xslArg = new XsltArgumentList();
foreach (var functionsDefinition in functionsDefinitions)
{
if (functionsDefinition.Container is
IOrigamDependentXsltFunctionContainer origamContainer)
{
origamContainer.TransactionId = transactionId;
}
xslArg.AddExtensionObject(
functionsDefinition.NameSpaceUri, functionsDefinition.Container);
}
xslArg.AddExtensionObject(ExsltNamespaces.DatesAndTimes,
new ExsltDatesAndTimes());
xslArg.AddExtensionObject(ExsltNamespaces.Strings, new ExsltStrings());
xslArg.AddExtensionObject(ExsltNamespaces.RegularExpressions,
new ExsltRegularExpressions());
xslArg.AddExtensionObject(ExsltNamespaces.Math, new ExsltMath());
xslArg.AddExtensionObject(ExsltNamespaces.Random, new ExsltRandom());
xslArg.AddExtensionObject(ExsltNamespaces.Sets, new ExsltSets());
xslArg.AddExtensionObject(ExsltNamespaces.GdnDatesAndTimes,
new GdnDatesAndTimes());
xslArg.AddExtensionObject(ExsltNamespaces.GdnMath, new GdnMath());
xslArg.AddExtensionObject(ExsltNamespaces.GdnRegularExpressions,
new GdnRegularExpressions());
xslArg.AddExtensionObject(ExsltNamespaces.GdnSets, new GdnSets());
xslArg.AddExtensionObject(ExsltNamespaces.GdnStrings, new GdnStrings());
xslArg.AddExtensionObject(ExsltNamespaces.GdnDynamic, new GdnDynamic());
return xslArg;
}
private void TraceResult(IXmlContainer traceDocument)
{
StringBuilder b = new StringBuilder();
StringWriter swr = new StringWriter(b);
XmlTextWriter xwr = new XmlTextWriter(swr);
xwr.Formatting = Formatting.Indented;
traceDocument.Xml.WriteTo(xwr);
xwr.Close();
swr.Close();
TracingService.TraceStep(this.TraceWorkflowId, this.TraceStepName,
this.TraceStepId, "Transformation Service", "Output", null, b.ToString(), null, null);
}
public abstract void Transform(object engine, XsltArgumentList xslArg, XPathDocument sourceXpathDoc, XmlTextWriter xwr);
public abstract void Transform(object engine, XsltArgumentList xslArg, XPathDocument sourceXpathDoc, IXmlContainer resultDoc);
public abstract void Transform(object engine, XsltArgumentList xslArg, IXPathNavigable input, Stream output);
}
}