-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathRazorEngine.cs
More file actions
761 lines (647 loc) · 30.4 KB
/
RazorEngine.cs
File metadata and controls
761 lines (647 loc) · 30.4 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
#pragma warning disable CS1591
#region License
/*
**************************************************************
* Author: Rick Strahl
* © West Wind Technologies, 2010-2011
* http://www.west-wind.com/
*
* Created: 1/4/2010
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
#pragma warning disable CS1591
using System;
using System.Text;
using System.Linq;
using System.Web.Razor.Generator;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Web.Razor;
using Westwind.RazorHosting.Properties;
namespace Westwind.RazorHosting
{
/// <summary>
/// Razor Hosting Engine that allows execution of Razor templates outside of
/// ASP.NET. You can execute templates from string or a textreader and output
/// to string or a text reader.
///
/// This implementation only supports C#.
/// </summary>
public class RazorEngine : RazorEngine<RazorTemplateBase>
{
public RazorEngine() : base()
{ }
public RazorEngine(CSharpCodeProvider codeProvider) :base(codeProvider)
{
}
}
/// <summary>
/// Razor Hosting Engine that allows execution of Razor templates outside of
/// ASP.NET. You can execute templates from string or a textreader and output
/// to string or a text reader.
///
/// This implementation only supports C#.
/// </summary>
/// <typeparam name="TBaseTemplateType">RazorTemplateHost based type</typeparam>
public class RazorEngine<TBaseTemplateType> : MarshalByRefObject
where TBaseTemplateType : RazorTemplateBase
{
/// <summary>
/// Any errors that occurred during template execution
/// </summary>
public string ErrorMessage {get; set; }
/// <summary>
/// Last generated output
/// </summary>
public string LastGeneratedCode
{
get => Utilities.GetTextWithLineNumbers(_LastGeneratedCode);
set => _LastGeneratedCode = value;
}
private string _LastGeneratedCode;
/// <summary>
/// Allows retrieval of the template's ResultData property
/// to be retrieved from the last request.
/// </summary>
public dynamic LastResultData { get; set; }
/// <summary>
/// Holds Razor Configuration Properties
/// </summary>
public RazorEngineConfiguration Configuration { get; set; }
/// <summary>
/// Provide a reference to a RazorHost container so that it
/// can be passed to a template.
///
/// This may be null, but if a container is available this value
/// is set and passed on to the template as HostContainer.
/// </summary>
public object HostContainer {get; set; }
/// <summary>
/// The code provider used with this instance
/// </summary>
internal CSharpCodeProvider CodeProvider { get; set; }
/// <summary>
/// A list of default namespaces to include
///
/// Defaults already included:
/// System, System.Text, System.IO, System.Collections.Generic, System.Linq
/// </summary>
internal List<string> ReferencedNamespaces { get; set; }
/// <summary>
/// A list of default assemblies referenced during compilation
///
/// Defaults already included:
/// System, System.Text, System.IO, System.Collections.Generic, System.Linq
/// </summary>
internal List<string> ReferencedAssemblies { get; set; }
/// <summary>
/// Internally cache assemblies loaded with ParseAndCompileTemplate.
/// Assemblies are cached in the EngineHost so they don't have
/// to cross AppDomains for invocation when running in a separate AppDomain
/// </summary>
protected Dictionary<string, Assembly> AssemblyCache { get; set; }
/// <summary>
/// A property that holds any per request configuration
/// data that is to be passed to the template. This object
/// is passed to InitializeTemplate after the instance was
/// created.
///
/// This object must be serializable.
/// This object should be set on every request and cleared out after
/// each request
/// </summary>
public object TemplatePerRequestConfigurationData { get; set; }
/// <summary>
/// Creates an instance of the host and performs basic configuration
/// Optionally pass in any required namespaces and assemblies by name
/// </summary>
public RazorEngine(CSharpCodeProvider codeProvider = null)
{
Configuration = new RazorEngineConfiguration();
AssemblyCache = new Dictionary<string, Assembly>();
ErrorMessage = string.Empty;
ReferencedNamespaces = new List<string>();
ReferencedNamespaces.Add("System");
ReferencedNamespaces.Add("System.Text");
ReferencedNamespaces.Add("System.Collections.Generic");
ReferencedNamespaces.Add("System.Linq");
ReferencedNamespaces.Add("System.IO");
ReferencedNamespaces.Add("Westwind.RazorHosting"); // this namespace
ReferencedAssemblies = new List<string>();
ReferencedAssemblies.Add("System.dll");
ReferencedAssemblies.Add("System.Core.dll");
ReferencedAssemblies.Add("Microsoft.CSharp.dll"); // dynamic support!
ReferencedAssemblies.Add(typeof(RazorEngineHost).Assembly.Location);
ReferencedAssemblies.Add(typeof(RazorEngine).Assembly.Location);
CodeProvider = codeProvider;
if (CodeProvider == null)
CodeProvider = new CSharpCodeProvider();
}
/// <summary>
/// Method to add assemblies to the referenced assembly list.
/// Use the DLL name or strongly typed name. Assembly added HAS
/// to be accessible via GAC or in bin/privatebin path
/// </summary>
/// <param name="assemblyPath">
/// Path to the assembly. GAC'd assemblies or assemblies in current path
/// can be provided without a path. All others should contain a fully qualified OS path.
/// Note that Razor does not look in the PrivateBin path for the AppDomain.
/// </param>
/// <param name="additionalAssemblies">Additional assembly paths to add </param>
public void AddAssembly(string assemblyPath, params string[] additionalAssemblies)
{
ReferencedAssemblies.Add(assemblyPath);
if (additionalAssemblies != null)
ReferencedAssemblies.AddRange(additionalAssemblies);
}
/// <summary>
/// Adds an assembly to the Referenced assemblies based on a type
/// reference. Useful to add the 'host' assembly and model types.
/// </summary>
/// <param name="type"></param>
public void AddAssemblyFromType(Type type)
{
if (type != null)
{
string assemblyFile = type.Assembly.Location;
string justFile = Path.GetFileName(assemblyFile).ToLower();
if (!ReferencedAssemblies.Where(s => s.ToLower().Contains(justFile)).Any())
ReferencedAssemblies.Add(assemblyFile);
}
}
/// <summary>
/// Adds an assembly to the ReferenceAssemblies based on an object instance.
/// Easy way to add a model's assembly.
/// </summary>
/// <param name="instance">any object instance</param>
public void AddAssemblyFromType(object instance)
{
if (instance != null)
{
string assemblyFile = instance.GetType().Assembly.Location;
string justFile = Path.GetFileName(assemblyFile).ToLower();
if (!ReferencedAssemblies.Where(s => s.ToLower().Contains(justFile)).Any())
ReferencedAssemblies.Add(assemblyFile);
}
}
/// <summary>
/// Method to add namespaces to the compiled code.
/// Add namespaces to minimize explicit namespace
/// requirements in your Razor template code.
///
/// Make sure that any required assemblies are
/// loaded first.
/// </summary>
/// <param name="ns">First namespace</param>
/// <param name="additionalNamespaces">additional namespaces</param>
public void AddNamespace(string ns,params string[] additionalNamespaces)
{
ReferencedNamespaces.Add(ns);
if (additionalNamespaces != null)
{
foreach (string ans in additionalNamespaces)
{
ReferencedNamespaces.AddRange(additionalNamespaces);
}
}
}
/// <summary>
/// Method to add namespaces to the compiled code.
/// Add namespaces to minimize explicit namespace
/// requirements in your Razor template code.
///
/// Make sure that any required assemblies are
/// loaded first.
/// </summary>
/// <param name="additionalNamespaces">additional namespaces</param>
public void AddNamespace(params string[] additionalNamespaces)
{
//ReferencedNamespaces.Add(ns);
if (additionalNamespaces != null)
{
foreach (string ans in additionalNamespaces)
{
ReferencedNamespaces.Add(ans);
}
}
}
/// <summary>
/// Execute a template based on a TextReader input into a provided TextWriter object.
/// </summary>
/// <param name="templateSourceReader">A text reader that reads in the markup template</param>
/// <param name="model">Optional model available in the template as this.Context</param>
/// <param name="outputWriter">
/// A text writer that receives the rendered template output.
/// Writer is closed after rendering.
/// When provided the result of this method is string.Empty (success) or null (failure)
/// </param>
/// <returns>output from template. If an outputWriter is passed in result is string.Empty on success, null on failure</returns>
public string RenderTemplate(
TextReader templateSourceReader,
object model = null,
TextWriter outputWriter = null)
{
SetError();
AddAssemblyFromType(model);
var assemblyId = CompileTemplate(templateSourceReader);
if (assemblyId == null)
return null;
return RenderTemplateFromAssembly(assemblyId, model, outputWriter);
}
/// <summary>
/// Execute a template based on a TextReader input into a provided TextWriter object.
/// </summary>
/// <param name="templateText">A string that contains the markup template</param>
/// <param name="model">Optional model available in the template as this.Context</param>
/// <param name="outputWriter">
/// A text writer that receives the rendered template output.
/// Writer is closed after rendering.
/// When provided the result of this method is string.Empty (success) or null (failure)
/// </param>
/// <param name="inferModelType">If true, tries to infer the model type when no @model or @inherits tags are defined for the template</param>
/// <returns>output from template. If an outputWriter is passed in result is string.Empty on success, null on failure</returns>
public string RenderTemplate(
string templateText,
object model = null,
TextWriter outputWriter = null,
bool inferModelType = false)
{
if (inferModelType && model != null &&
!templateText.Trim().StartsWith("@model") &&
!templateText.Trim().StartsWith("@inherits"))
templateText = "@model " + model.GetType().FullName + "\r\n"+ templateText ;
TextReader templateReader = new StringReader(templateText);
return RenderTemplate(templateReader, model, outputWriter);
}
/// <summary>
/// Executes a template based on a previously compiled and cached assembly reference.
/// This effectively allows you to cache an assembly.
/// </summary>
/// <param name="assemblyId">Id of an existing assembly that was previously compiled</param>
/// <param name="model">The model to use</param>
/// <param name="outputWriter">A text writer that receives output generated by the template. Writer is closed after rendering.</param>
/// <param name="generatedNamespace"></param>
/// <param name="generatedClass"></param>
/// <returns>output from template. If an outputWriter is passed in result is string.Empty on success, null on failure</returns>
public string RenderTemplateFromAssembly(
string assemblyId,
object model,
TextWriter outputWriter = null,
string generatedNamespace = null,
string generatedClass = null)
{
SetError();
// Handle anonymous and other non-public types
if (model != null && model.GetType().IsNotPublic)
model = new AnonymousDynamicType(model);
Assembly generatedAssembly = AssemblyCache[assemblyId];
if (generatedAssembly == null)
{
SetError(Resources.PreviouslyCompiledAssemblyNotFound);
return null;
}
// find the generated type to instantiate
Type type = null;
if (string.IsNullOrEmpty(generatedNamespace) || string.IsNullOrEmpty(generatedClass))
{
type = generatedAssembly.GetTypes().FirstOrDefault();
if (type == null)
{
SetError(Resources.UnableToCreateType);
return null;
}
}
else
{
string className = generatedNamespace + "." + generatedClass;
try
{
type = generatedAssembly.GetType(className);
}
catch (Exception ex)
{
SetError(Resources.UnableToCreateType + className + ": " + ex.Message);
return null;
}
}
// Start with empty non-error response (if we use a writer)
string result = string.Empty;
using (TBaseTemplateType instance = InstantiateTemplateClass(type))
{
if (instance == null)
throw new InvalidOperationException(ErrorMessage);
//if (TemplatePerRequestConfigurationData != null)
instance.InitializeTemplate(model, TemplatePerRequestConfigurationData);
if (outputWriter != null)
instance.Response.SetTextWriter(outputWriter);
if (!InvokeTemplateInstance(instance, model))
return null;
// Capture string output if implemented and return
// otherwise null is returned
if (outputWriter == null)
result = instance.Response.ToString();
else
// return string.Empty for success if a writer is provided
result = string.Empty;
}
return result;
}
/// <summary>
/// Parses and compiles a markup template into an assembly and returns
/// an assembly name. The name is an ID that can be passed to
/// ExecuteTemplateByAssembly which picks up a cached instance of the
/// loaded assembly.
///
/// </summary>
/// <param name="templateReader">Textreader that loads the template</param>
/// <param name="generatedNamespace">The namespace of the class to generate from the template. null generates name.</param>
/// <param name="generatedClassName">The name of the class to generate from the template. null generates name.</param>
/// <remarks>
/// The actual assembly isn't returned here to allow for cross-AppDomain
/// operation. If the assembly was returned it would fail for cross-AppDomain
/// calls.
/// </remarks>
/// <returns>An assembly Id. The Assembly is cached in memory and can be used with RenderFromAssembly.</returns>
public string CompileTemplate(
TextReader templateReader,
string generatedNamespace = null,
string generatedClassName = null)
{
if (string.IsNullOrEmpty(generatedNamespace))
generatedNamespace = "__RazorHost";
if (string.IsNullOrEmpty(generatedClassName))
generatedClassName = GetSafeClassName(null);
else
generatedClassName = GetSafeClassName(generatedClassName);
RazorTemplateEngine engine = CreateHost(generatedNamespace, generatedClassName);
string template = templateReader.ReadToEnd();
templateReader.Close();
template = FixupTemplate(template);
var reader = new StringReader(template);
// Generate the template class as CodeDom
GeneratorResults razorResults = engine.GenerateCode(reader);
reader.Close();
// Create code from the codeDom and compile
// var codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
var codeProvider = CodeProvider;
if (codeProvider == null)
codeProvider = new CSharpCodeProvider();
var options = new CodeGeneratorOptions();
// Capture Code Generated as a string for error info
// and debugging
LastGeneratedCode = null;
using (var writer = new StringWriter())
{
codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
LastGeneratedCode = writer.ToString();
}
var compilerParameters = CreateCompilerParameters();
CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
if (compilerResults.Errors.Count > 0)
{
var compileErrors = new StringBuilder();
foreach (CompilerError compileError in compilerResults.Errors)
compileErrors.AppendLine(String.Format("Line: {0}, Column: {1}, Error: {2}",
compileError.Line,
compileError.Column,
compileError.ErrorText));
SetError(compileErrors.ToString());
return null;
}
AssemblyCache.Add(compilerResults.CompiledAssembly.FullName, compilerResults.CompiledAssembly);
return compilerResults.CompiledAssembly.FullName;
}
/// <summary>
/// Parses and compiles a markup template into an assembly and returns
/// an assembly name. The name is an ID that can be passed to
/// ExecuteTemplateByAssembly which picks up a cached instance of the
/// loaded assembly.
///
/// </summary>
/// <param name="templateText">Text of the template to render</param>
/// <param name="generatedNamespace">Namespace for the generated class. If not passed will be __RazorHosting</param>
/// <param name="generatedClassName">Classname for the generated class. If not passed will be a generated unique name based on GUID</param>
/// <remarks>
/// The actual assembly isn't returned here to allow for cross-AppDomain
/// operation. If the assembly was returned it would fail for cross-AppDomain
/// calls.
/// </remarks>
/// <returns>An assembly Id. The Assembly is cached in memory and can be used with RenderFromAssembly.</returns>
public string CompileTemplate(string templateText,
string generatedNamespace = null,
string generatedClassName = null)
{
using (StringReader reader = new StringReader(templateText))
{
return CompileTemplate(reader, generatedNamespace, generatedClassName);
}
}
/// <summary>
/// Creates an instance of the RazorHost with various options applied.
/// Applies basic namespace imports and the name of the class to generate
/// </summary>
/// <param name="generatedNamespace"></param>
/// <param name="generatedClass"></param>
/// <param name="baseClassType"></param>
/// <returns></returns>
protected RazorTemplateEngine CreateHost(string generatedNamespace, string generatedClass, Type baseClassType = null)
{
if (baseClassType == null)
baseClassType = typeof(TBaseTemplateType);
RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());
host.DefaultBaseClass = baseClassType.FullName;
host.DefaultClassName = generatedClass;
host.DefaultNamespace = generatedNamespace;
var context = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", typeof(HelperResult).FullName, "DefineSection");
context.ResolveUrlMethodName = "ResolveUrl";
host.GeneratedClassContext = context;
foreach (string ns in ReferencedNamespaces)
{
host.NamespaceImports.Add(ns);
}
return new RazorTemplateEngine(host);
}
/// <summary>
/// Allows retrieval of an Assembly cached internally by its id
/// returned from ParseAndCompileTemplate. Useful if you want
/// to write an assembly to disk for later activation
/// </summary>
/// <param name="assemblyId"></param>
public Assembly GetAssemblyFromId(string assemblyId)
{
Assembly ass = null;
AssemblyCache.TryGetValue(assemblyId, out ass);
return ass;
}
/// <summary>
/// Overridable instance creation routine for the host.
///
/// Handle custom template base classes (derived from RazorTemplateBase)
/// and setting of properties on the instance in subclasses by overriding
/// this method.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected virtual TBaseTemplateType InstantiateTemplateClass(Type type)
{
object inst = Activator.CreateInstance(type);
TBaseTemplateType instance = inst as TBaseTemplateType;
if (instance == null)
{
SetError(Resources.CouldnTActivateTypeInstance + type.FullName);
return null;
}
instance.Engine = this;
// If a HostContainer was set pass that to the template too
instance.HostContainer = HostContainer;
return instance;
}
/// <summary>
/// Internally executes an instance of the template,
/// captures errors on execution and returns true or false
/// </summary>
/// <param name="instance">An instance of the generated template</param>
/// <param name="model"></param>
/// <returns>true or false - check ErrorMessage for errors</returns>
protected virtual bool InvokeTemplateInstance(TBaseTemplateType instance, object model)
{
LastException = null;
LastResultData = null;
try
{
instance.Model = model;
if (model != null)
{
//instance.Model = model;
// USE DYNAMIC HERE TO AVOID TYPECASTING ERRORS OF THE MODEL
// WHEN SERIALIZING
//// if there's a model property try to
//// assign it from model
dynamic dynInstance = instance;
dynamic dcontext = model;
dynInstance.Model = dcontext;
}
instance.Execute();
}
catch (Exception ex)
{
LastException = ex;
SetError(Resources.TemplateExecutionError + ex.Message);
return false;
}
finally
{
// Must make sure Response is closed
instance.Response.Dispose();
}
// capture result data so the engine can
// pass it back to the caller
LastResultData = instance.ResultData;
return true;
}
/// <summary>
/// Override to allow indefinite lifetime - no unloading
/// </summary>
/// <returns></returns>
public override object InitializeLifetimeService()
{
return null;
}
/// <summary>
/// Internally fix ups for templates
/// </summary>
/// <param name="template"></param>
/// <returns></returns>
protected virtual string FixupTemplate(string template)
{
// @model fixup
if (template.Contains("@model "))
{
int at = template.IndexOf("@model ");
int at2 = template.IndexOf("\n", at);
var line = template.Substring(at, at2 - at);
var modelClass = line.Replace("@model ", "").Trim();
var templateType = typeof(TBaseTemplateType);
var newline = "@inherits " +
(!string.IsNullOrEmpty(templateType.Namespace) ? templateType.Namespace + "." : "") +
templateType.Name + "<" + modelClass + ">";
template = template.Replace(line, newline);
}
return template;
}
/// <summary>
/// Returns a unique ClassName for a template to execute
/// Optionally pass in an objectId on which the code is based
/// or null to get default behavior.
///
/// Default implementation just returns Guid as string
/// </summary>
/// <param name="objectId"></param>
/// <returns></returns>
protected virtual string GetSafeClassName(object objectId)
{
return "_" + Guid.NewGuid().ToString().Replace("-", "_");
}
/// <summary>
/// Sets error information consistently
/// </summary>
/// <param name="message"></param>
public void SetError(string message)
{
if (message == null)
ErrorMessage = string.Empty;
else
ErrorMessage = message;
}
public void SetError()
{
SetError(null);
}
public Exception LastException { get; set; }
protected virtual CompilerParameters CreateCompilerParameters()
{
var compilerParameters = new CompilerParameters(ReferencedAssemblies.ToArray());
//compilerParameters.IncludeDebugInformation = true;
compilerParameters.GenerateInMemory = Configuration.CompileToMemory;
if (!Configuration.CompileToMemory)
compilerParameters.OutputAssembly = Path.Combine(Configuration.TempAssemblyPath, "_" + Guid.NewGuid().ToString("n") + ".dll");
if (Configuration.TempFiles != null)
compilerParameters.TempFiles = Configuration.TempFiles;
return compilerParameters;
}
}
public enum CodeProvider
{
CSharp,
VisualBasic
}
//public class Foo : MarshalByRefObject
//{
// public string Name { get; set; }
//}
}