public MvcCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     // set the default model type to "dynamic" (Dev10 bug 935656)
     // don't set it for "special" pages (such as "_viewStart.cshtml")
     SetBaseType(DefaultModelTypeName);
 }
 public GeneratorResults ParseToCode(string TemplateCode, string defaultnamespace, string defaultclassname, string baseClassFullName)
 {
     GeneratorResults razorResults;
     var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     host.DefaultBaseClass = baseClassFullName;//typeof(BulaqTemplateForRazorBase).FullName;
     host.DefaultNamespace = defaultnamespace;
     host.DefaultClassName = defaultclassname;
     host.NamespaceImports.Add("System");
     host.NamespaceImports.Add("BulaqCMS.Models");
     host.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral");
     var engine = new RazorTemplateEngine(host);
     using (var reader = new StringReader(TemplateCode))
     {
         razorResults = engine.GenerateCode(reader);
         CSharpCodeProvider codeProvider = new CSharpCodeProvider();
         CodeGeneratorOptions options = new CodeGeneratorOptions();
         options.BracingStyle = "C";
         using (StringWriter writer = new StringWriter())
         {
             IndentedTextWriter indentwriter = new IndentedTextWriter(writer, "    ");
             codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, indentwriter, options);
             indentwriter.Flush();
             indentwriter.Close();
             LastGeneratedCode = writer.GetStringBuilder().ToString();
             string codePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\code.cs";
             File.WriteAllText(codePath, LastGeneratedCode, Encoding.UTF8);
         }
     }
     return razorResults;
 }
Exemple #3
0
        private static GeneratorResults GenerateCode(RazorTemplateEntry entry, Type baseType)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            host.DefaultBaseClass = baseType.FullName;
            host.DefaultNamespace = "TeamConfig.Razor.Template";
            host.DefaultClassName = entry.TemplateName + "Template";
            host.NamespaceImports.Add("System");

            //filter out page directives and add them as namespace
            string templateString = entry.TemplateString;
            foreach (Match match in PageDirectivePattern.Matches(templateString))
            {
                string usedNamespace = match.Groups["Namespace"].Value;
                templateString = templateString.Replace(match.Value, string.Empty);
                if (usedNamespace.StartsWith("using"))
                {
                    host.NamespaceImports.Add(usedNamespace);
                }
            }

            GeneratorResults razorResult = null;

            using (TextReader reader = new StringReader(templateString))
            {
                var templateEngine = new RazorTemplateEngine(host);
                razorResult = templateEngine.GenerateCode(reader);
            }
            return razorResult;
        }
        public BackgroundParser(RazorEngineHost host, string fileName)
        {
            _main = new MainThreadState(fileName);
            _bg = new BackgroundThread(_main, host, fileName);

            _main.ResultsReady += (sender, args) => OnResultsReady(args);
        }
 public SimpleCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     var baseType = new CodeTypeReference("SimpleTemplateModelBase<dynamic>");
     Context.GeneratedClass.BaseTypes.Clear();
     Context.GeneratedClass.BaseTypes.Add(baseType);
 }
        public Type Compile(string className, CodeCompileUnit codeCompileUnit, RazorEngineHost host)
        {
            var compilerParameters = new CompilerParameters {GenerateInMemory = true, CompilerOptions = "/optimize"};
            AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic)
                .Each(x => compilerParameters.ReferencedAssemblies.Add(x.Location));

            CompilerResults compilerResults;
            using (var codeDomProvider = Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType).As<CodeDomProvider>())
            {
                compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit);
                if (compilerResults.Errors.HasErrors)
                {
                    using (var sw = new StringWriter())
                    using (var tw = new IndentedTextWriter(sw, "    "))
                    {
                        codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, tw, new CodeGeneratorOptions());
                        var source = sw.ToString();
                        throw CreateExceptionFromCompileError(compilerResults, source);
                    }
                }
            }

            var templateTypeName = "{0}.{1}".ToFormat(host.DefaultNamespace, className);
            var templateType = compilerResults.CompiledAssembly.GetType(templateTypeName);
            return templateType;
        }
Exemple #7
0
 public Engine()
 {
     _host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     _host.DefaultBaseClass = "MiniMvc.ViewBase";
     //_host.GeneratedClassContext = new System.Web.Razor.Generator.GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "something", "DefineSection", "BeginContext", "EndContext");
     _host.GeneratedClassContext = new System.Web.Razor.Generator.GeneratedClassContext("Execute", "Write", "WriteLiteral", null, null, null, "DefineSection", null, null);
 }
 public HtmlMinifierMvcCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName,
     RazorEngineHost host, IHtmlPageMinifier htmlPageMinifier, IDebugStatusReader debugStatusReader)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     m_HtmPagelMinifier = htmlPageMinifier;
     m_DebugStatusReader = debugStatusReader;
 }
        public static ParsedTemplate parse(string sourceFilename, string cshtmlContent, string effectiveTemplateClassName, Type modelType)
        {
            var csCodeLanguage = new CSharpRazorCodeLanguage();
            var templateHost = new RazorEngineHost(csCodeLanguage, () => new HtmlMarkupParser());

            var concreteBaseClassType = getBaseClassTypeFromModel(modelType);
            templateHost.DefaultBaseClass = concreteBaseClassType.FullName;

            var templateEngine = new RazorTemplateEngine(templateHost);

            var trimmedcshtmlContent = HeaderLines.trim(cshtmlContent);

            GeneratorResults res;
            using (var input = new StringReader(trimmedcshtmlContent))
            {
                res = templateEngine.GenerateCode(input, effectiveTemplateClassName, GeneratedTemplateNamespace, sourceFilename);
            }

            if (!res.Success)
                throw new Exception("Failed to generate code");

            var compileUnit = res.GeneratedCode;
            var fullyQualifiedClassName = GeneratedTemplateNamespace + "." + effectiveTemplateClassName;

            return new ParsedTemplate(fullyQualifiedClassName, compileUnit);
        }
 public SimpleCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     var baseType = new CodeTypeReference(SimpleRazorConfiguration.BaseClass);
     Context.GeneratedClass.BaseTypes.Clear();
     Context.GeneratedClass.BaseTypes.Add(baseType);
 }
Exemple #11
0
		void ReadHtmlSpans(string html)
		{
			RazorEngineHost razorEngineHost = new RazorEngineHost(codeLanguage);
			RazorTemplateEngine engine = new RazorTemplateEngine(razorEngineHost);
			ParserResults results = engine.ParseTemplate(new StringReader(html));
			spans = new List<Span>(results.Document.Flatten());
			spans.RemoveAll(span => span.Kind != SpanKind.Markup);
		}
 public SimpleRazorBuildProvider()
 {
     this._codeLanguage = new CSharpRazorCodeLanguage();
     this._compilerType = GetDefaultCompilerTypeForLanguage(this._codeLanguage.LanguageName);
     this._host = new SimpleRazorEngineHost(this._codeLanguage);
     this._virtualPathDependencies = null;
     this._typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this._host.DefaultNamespace, "Foot");
 }
Exemple #13
0
 void ReadBlockSpans(string markup)
 {
     var razorEngineHost = new RazorEngineHost(codeLanguage);
     var engine = new RazorTemplateEngine(razorEngineHost);
     var results = engine.ParseTemplate(new StringReader(markup));
     spans = new List<Span>(results.Document.Flatten());
     spans.RemoveAll(span => !span.IsBlock);
 }
 public MvcCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
     : base(className, rootNamespaceName, sourceFileName, host) {
     var mvcHost = host as MvcWebPageRazorHost;
     if (mvcHost != null && !mvcHost.IsSpecialPage) {
         // set the default model type to "dynamic" (Dev10 bug 935656)
         // don't set it for "special" pages (such as "_viewStart.cshtml")
         SetBaseType(_defaultModelTypeName);
     }
 }
        /// <summary>
        /// Constructs a new RazorTemplateEngine with the specified host
        /// </summary>
        /// <param name="host">The host which defines the environment in which the generated template code will live</param>
        public RazorTemplateEngine(RazorEngineHost host)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            Host = host;
        }
        /// <summary>
        /// Gets the generator result.
        /// </summary>
        /// <param name="host">The razor engine host.</param>
        /// <param name="template">The template.</param>
        /// <returns>The generator result.</returns>
        private static GeneratorResults GetGeneratorResult(System.Web.Razor.RazorEngineHost host, string template)
        {
            var engine = new RazorTemplateEngine(host);
            GeneratorResults result;

            using (var reader = new StringReader(template))
                result = engine.GenerateCode(reader);

            return(result);
        }
        public HtmlOptimizerMvc4CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, IMinifier minifier)
            : base(className, rootNamespaceName, sourceFileName, host)
        {
            var webPageRazorHost = host as MvcWebPageRazorHost;
              if (webPageRazorHost == null || webPageRazorHost.IsSpecialPage)
            return;
              this.SetBaseType("dynamic");

              _minifier = minifier;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="CSharpRazorBuildProvider"/> class.
		/// </summary>
		public CSharpRazorBuildProvider()
		{
			this.compilerType = this.GetDefaultCompilerTypeForLanguage("C#");

			this.host = new RazorEngineHost(new CSharpRazorCodeLanguage()) {
				DefaultBaseClass = typeof(ViewPageRef).FullName,
				DefaultNamespace = "RazorOutput",
				DefaultClassName = "ViewPage"
			};
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="CSharpRazorCodeGenerator"/> class.
 /// </summary>
 /// <param name="className">Name of the class.</param>
 /// <param name="rootNamespaceName">Name of the root namespace.</param>
 /// <param name="sourceFileName">Name of the source file.</param>
 /// <param name="host">The host.</param>
 /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param>
 public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, bool strictMode)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     StrictMode = strictMode;
     var mvcHost = host as Compilation.RazorEngineHost;
     if (mvcHost != null)
     {
         SetBaseTypeFromHost(mvcHost);
     }
 }
 private RazorTemplateEngine InitializeRazorEngine(Type baseClassType, string namespaceOfGeneratedClass, string generatedClassName)
 {
     RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     host.DefaultBaseClass = baseClassType.FullName;
     host.DefaultClassName = generatedClassName;
     host.DefaultNamespace = namespaceOfGeneratedClass;
     host.NamespaceImports.Add("System");
     host.NamespaceImports.Add("System.Collections.Generic");
     host.NamespaceImports.Add("System.Linq");
     return new RazorTemplateEngine(host);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CSharpRazorCodeGenerator"/> class.
 /// </summary>
 /// <param name="className">Name of the class.</param>
 /// <param name="rootNamespaceName">Name of the root namespace.</param>
 /// <param name="sourceFileName">Name of the source file.</param>
 /// <param name="host">The host.</param>
 /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param>
 public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, bool strictMode)
     : base(className, rootNamespaceName, sourceFileName, host)
 {
     StrictMode = strictMode;
     var mvcHost = host as Compilation.RazorEngineHost;
     if (mvcHost != null)
     {
         // set the default model type to "dynamic"
         SetBaseType("dynamic");
     }
 }
Exemple #22
0
        internal void Parse(TextReader razorTemplate, TextWriter output)
        {
            RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            ParserResults result = engine.ParseTemplate(razorTemplate);

            if (!result.Success)
            {
                ThrowParserError(result);
            }
            WriteTemplateFunction(result.Document, output);
        }
        private static RazorTemplateEngine CreateEngine()
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage())
                           {
                               DefaultBaseClass = typeof (TemplateBase).FullName,
                               DefaultNamespace = "RazorOutput",
                               DefaultClassName = "Template"
                           };

            host.NamespaceImports.Add("System");

            return new RazorTemplateEngine(host);
        }
        public virtual void RenderClientTemplate(TextReader razorTemplate, TextWriter output)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            var engine = new RazorTemplateEngine(host);

            var parserResults = engine.ParseTemplate(razorTemplate);

            if(parserResults.Success == false)
                // TODO: Less suck
                throw new RazorClientTemplateException("Template parse exception");

            RenderClientTemplate(parserResults.Document, output);
        }
        /// <summary>
        /// Constructs the editor parser.  One instance should be used per active editor.  This
        /// instance _can_ be shared among reparses, but should _never_ be shared between documents.
        /// </summary>
        /// <param name="host">The <see cref="RazorEngineHost"/> which defines the environment in which the generated code will live.  <see cref="F:RazorEngineHost.DesignTimeMode"/> should be set if design-time code mappings are desired</param>
        /// <param name="sourceFileName">The physical path to use in line pragmas</param>
        public RazorEditorParser(RazorEngineHost host, string sourceFileName)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (String.IsNullOrEmpty(sourceFileName))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "sourceFileName");
            }

            Host = host;
            FileName = sourceFileName;
        }
Exemple #26
0
        public static RazorTemplateEngine CreateEngine()
        {
            var language = new CSharpRazorCodeLanguage();
            var host = new RazorEngineHost(language);
            host.DefaultBaseClass = typeof(RazorTemplate<Context>).FullName;
            host.DefaultNamespace = "RazorOutput";
            host.DefaultClassName = "Template";
            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.IO");
            //host.NamespaceImports.Add("System.Linq");
           // host.NamespaceImports.Add("System.Text.RegularExpressions");

            var engine = new RazorTemplateEngine(host);
            return engine;
        }
        private static RazorTemplateEngine GetRazorTemplateEngine()
        {
            RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());

            host.DefaultBaseClass = typeof(RazorViewBase).FullName;

            host.DefaultNamespace = "RazorOutput";
            host.DefaultClassName = "RazorView";

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.IO");
            host.NamespaceImports.Add("Microsoft.CSharp.RuntimeBinder");

            return new RazorTemplateEngine(host);
        }
            public MvcCodeGenerator(string className, string baseClass, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
                : base(className, rootNamespaceName, sourceFileName, host)
            {
                string baseType;

                if (IsSpecialPage(sourceFileName))
                {
                    baseType = typeof(ViewStartPage).FullName;
                }
                else
                {
                    baseType = baseClass + '<' + DefaultModelTypeName + '>';
                }
                SetBaseType(baseType);
            }
Exemple #29
0
        // Returns an instance of the razor template, compiled from the file stored as an embedded resource.
        // The first time this method is executed, the Razor template is compiled and stored.
        // This method will throw an InvalidDataException if the template contains syntax errors.
        public TemplateBase CreateRazorTemplateInstance()
        {
            if (templateType == null)
            {
                var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
                host.DefaultBaseClass = typeof(TemplateBase).FullName;
                host.DefaultNamespace = "RazorOutput";
                host.DefaultClassName = "Template";
                host.NamespaceImports.Add("System");

                GeneratorResults razorResult = null;

                var templateStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Curtsy.Resources.curtsy.cshtml");

                if (templateStream == null)
                    throw new FileNotFoundException("Could not find embedded resource 'Curtsy.Resources.curtsy.cshtml'");

                using (var reader = new StreamReader(templateStream))
                {
                    razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
                }

                var compilerParams = new CompilerParameters
                {
                    GenerateInMemory = true,
                    GenerateExecutable = false,
                    IncludeDebugInformation = false,
                    CompilerOptions = "/target:library /optimize"
                };
                compilerParams.ReferencedAssemblies.Add(typeof(Program).Assembly.CodeBase.Replace("file:///", "").Replace('/', Path.DirectorySeparatorChar));

                var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                var results = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

                if (results.Errors.HasErrors)
                {
                    StringBuilder errors = new StringBuilder();
                    foreach (var err in results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning))
                        errors.AppendFormat("Error compiling template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);

                    throw new InvalidDataException(errors.ToString());
                }

                templateType = results.CompiledAssembly.GetType("RazorOutput.Template");
            }

            return (TemplateBase)Activator.CreateInstance(templateType);
        }
        public GeneratorResults GenerateCode(RazorTemplate descriptor, string className, RazorEngineHost host)
        {
            var engine = new RazorTemplateEngine(host);
             GeneratorResults results;
             using (var fileStream = new FileStream(descriptor.FilePath, FileMode.Open, FileAccess.Read))
             using (var reader = new StreamReader(fileStream))
             {
                 results = engine.GenerateCode(reader, className, host.DefaultNamespace, descriptor.ViewPath);
             }

             if (!results.Success)
             {
                 throw CreateExceptionFromParserError(results.ParserErrors.Last(), descriptor.Name());
             }
             return results;
        }
        public RazorTemplatesCompiler(string templatesNamespaceName, Type defaultTemplatesBaseClass)
        {
            _templatesNamespaceName = templatesNamespaceName;

            var razorHost = new RazorEngineHost(new CSharpRazorCodeLanguage())
                {
                    DefaultBaseClass = defaultTemplatesBaseClass.Name,
                    GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral",
                                                                      "WriteTo", "WriteLiteralTo",
                                                                      null,
                                                                      "DefineSection")
                };

            string[] namespaces = new[]
                {
                    "System",
                    "System.Collections.Generic",
                    "System.Linq",
                    "System.Text"
                };
            foreach (var ns in namespaces)
            {
                razorHost.NamespaceImports.Add(ns);
            }

            _razorEngine = new RazorTemplateEngine(razorHost);

            string[] references = new[]
                {
                    "System.Core.dll",
                    "Microsoft.CSharp.dll"
                };

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            _compilerParameters = new CompilerParameters(assemblies
                                                                  .Where(x => !x.IsDynamic)
                                                                  .Where(a => !references.Contains(a.ManifestModule.Name))
                                                                  .Select(a => new Uri(a.CodeBase).LocalPath)
                                                                  .Distinct()
                                                                  .ToArray())
                {
                    GenerateInMemory = true
                };

            _compilerParameters.ReferencedAssemblies.AddRange(references);
        }
Exemple #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CSharpRazorCodeGenerator"/> class.
        /// </summary>
        /// <param name="className">Name of the class.</param>
        /// <param name="rootNamespaceName">Name of the root namespace.</param>
        /// <param name="sourceFileName">Name of the source file.</param>
        /// <param name="host">The host.</param>
        /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param>
        public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, System.Web.Razor.RazorEngineHost host, bool strictMode)
            : base(className, rootNamespaceName, sourceFileName, host)
        {
            StrictMode = strictMode;
            var mvcHost = host as Compilation.RazorEngineHost;

            if (mvcHost != null)
            {
                SetBaseTypeFromHost(mvcHost);
            }
        }
 /// <summary>
 /// Constructs the code generator.  Must return a new instance on EVERY call to ensure thread-safety
 /// </summary>
 public abstract RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host);
 /// <summary>
 /// Constructs a new instance of the code generator for this language with the specified settings
 /// </summary>
 public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
 {
     return(new CSharpRazorCodeGenerator(className, rootNamespaceName, sourceFileName, host));
 }
Exemple #35
0
 internal virtual BackgroundParseTask CreateBackgroundTask(RazorEngineHost host, string fileName, TextChange change)
 {
     return(BackgroundParseTask.StartNew(new RazorTemplateEngine(Host), FileName, change));
 }