Beispiel #1
0
        /// <summary>
        /// Compiled the template template and add it to the cache
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="template"></param>
        public void CompileTemplate(string templateName, string template)
        {
            GeneratorResults razorResult = null;

            using (TextReader rdr = new StringReader(template)) {
                razorResult = _engine.GenerateCode(rdr);
            }
            var codeProvider = new CSharpCodeProvider();

            // Generate the code and put it in the text box:
            using (StringWriter sw = new StringWriter()) {
                codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, sw, new CodeGeneratorOptions());
                this.GeneratedCode = sw.GetStringBuilder().ToString();
            }
            var outputAssemblyName = String.Format(@"{0}\DSSharpLibrary_Razor_Template_{1}.dll", Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString("N"));

            var compilerParameters = new CompilerParameters(referencedAssemblies.ToArray(), outputAssemblyName);

            compilerParameters.GenerateInMemory        = true;
            compilerParameters.GenerateExecutable      = false;
            compilerParameters.IncludeDebugInformation = false;
            compilerParameters.CompilerOptions         = "/target:library /optimize";

            var compilerResult = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);

            if (compilerResult.Errors.HasErrors)
            {
                var sourceFileName = String.Format(@"{0}\DSSharpLibrary_Razor_Template_{1}.cs", Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString("N"));
                System.IO.File.WriteAllText(sourceFileName, this.GeneratedCode);

                CompilerError err = compilerResult.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).First();
                throw new ApplicationException(String.Format("Error Compiling Template: ({0}, {1}) {2}, C# file saved {3}", err.Line, err.Column, err.ErrorText, sourceFileName));
            }
            else
            {
                Type typ = compilerResult.CompiledAssembly.GetType("RazorOutput.Template");
                RazorTemplateBase newTemplate = Activator.CreateInstance(typ) as RazorTemplateBase;
                if (newTemplate == null)
                {
                    throw new ApplicationException("Could not construct RazorOutput.Template or it does not inherit from TemplateBase");
                }
                else
                {
                    Templates.Add(templateName, newTemplate);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Execute the template templateName. The template must have been previously
        /// compiled
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        public string Run(string templateName, object instance = null)
        {
            if (!Templates.ContainsKey(templateName))
            {
                throw new ApplicationException("Razor template is not defined");
            }

            var template          = this.Templates [templateName];
            RazorTemplateBase b   = template as RazorTemplateBase;
            ExpandoObject     bag = new ExpandoObject();           // Create a new blank bag
            var dictionaryBag     = bag as IDictionary <string, object>;

            b.bag = bag;
            IDictionary <string, object> dic = null;

            if ((instance != null) && (instance is ExpandoObject)) // Expando
            {
                dic = instance as IDictionary <string, object>;
            }

            else if (instance != null)                                  // Reflection
            {
                dic = DynamicSugar.ReflectionHelper.GetDictionary(instance);
            }

            if (dic != null)
            {
                foreach (KeyValuePair <string, object> i in dic)
                {
                    dictionaryBag.Add(i.Key, i.Value);
                }
            }

            template.Execute();
            var s = template.Buffer.ToString();

            template.Buffer.Clear();
            return(s);
        }