public MvcWebPageRazorHost(string virtualPath, string physicalPath)
            : base(virtualPath, physicalPath)
        {
            RegisterSpecialFile(RazorViewEngine.ViewStartFileName, typeof(ViewStartPage));

            DefaultPageBaseClass = typeof(WebViewPage).FullName;

            NamespaceImports.Add("System.Threading.Tasks");
            var context = GeneratedClassContext;

            if (!String.IsNullOrEmpty(context.ExecuteMethodName))
            {
                GeneratedClassContext = new GeneratedClassContext(context.ExecuteMethodName + "Async",
                                                                  context.WriteMethodName,
                                                                  context.WriteLiteralMethodName,
                                                                  context.WriteToMethodName,
                                                                  context.WriteLiteralToMethodName,
                                                                  context.TemplateTypeName,
                                                                  context.DefineSectionMethodName,
                                                                  context.BeginContextMethodName,
                                                                  context.EndContextMethodName)
                {
                    ResolveUrlMethodName = context.ResolveUrlMethodName
                };
            }
            // REVIEW get rid of the namespace import to not force additional references in default MVC projects
            GetRidOfNamespace("System.Web.WebPages.Html");
        }
Example #2
0
        public RazorTemplatingHost(Type baseType)
            : base(new CSharpRazorCodeLanguage())
        {
            if (baseType == null)
            {
                throw new ArgumentNullException(nameof(baseType));
            }

            DefaultBaseClass = baseType.FullName;

            //ToDo: Why Do I need templateTypeName? Do I need other parameters?
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "",
                generatedTagHelperContext: new GeneratedTagHelperContext())
            {
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #3
0
        public MvcRazorHost(string baseType)
            : base(new CSharpRazorCodeLanguage())
        {
            // TODO: this needs to flow from the application rather than being initialized here.
            // Tracked by #774
            _hostOptions          = new MvcRazorHostOptions();
            _baseType             = baseType;
            DefaultBaseClass      = baseType + '<' + _hostOptions.DefaultModel + '>';
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "HelperResult",
                defineSectionMethodName: "DefineSection")
            {
                ResolveUrlMethodName = "Href"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #4
0
 private void GetRidOfNamespace(string ns)
 {
     if (NamespaceImports.Contains(ns))
     {
         NamespaceImports.Remove(ns);
     }
 }
Example #5
0
        private WebPageRazorHost()
        {
            NamespaceImports.Add("System");
            NamespaceImports.Add("System.Collections.Generic");
            NamespaceImports.Add("System.IO");
            NamespaceImports.Add("System.Linq");
            NamespaceImports.Add("System.Net");
            NamespaceImports.Add("System.Web");
            NamespaceImports.Add("System.Web.Helpers");
            NamespaceImports.Add("System.Web.Security");
            NamespaceImports.Add("System.Web.UI");
            NamespaceImports.Add("System.Web.WebPages");
            NamespaceImports.Add("System.Web.WebPages.Html");

            DefaultNamespace      = WebDefaultNamespace;
            GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                              GeneratedClassContext.DefaultWriteMethodName,
                                                              GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                              WriteToMethodName,
                                                              WriteLiteralToMethodName,
                                                              TemplateTypeName,
                                                              DefineSectionMethodName);
            DefaultPageBaseClass    = PageBaseClass;
            DefaultDebugCompilation = true;
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of <see cref="MvcRazorHost"/> using the specified <paramref name="fileSystem"/>.
        /// </summary>
        /// <param name="fileSystem">A <see cref="IFileSystem"/> rooted at the application base path.</param>
        protected internal MvcRazorHost([NotNull] IFileSystem fileSystem)
            : base(new CSharpRazorCodeLanguage())
        {
            _fileSystem = fileSystem;
            _baseType   = BaseType;

            DefaultBaseClass      = BaseType + '<' + DefaultModel + '>';
            DefaultNamespace      = "Asp";
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Microsoft.AspNet.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection")
            {
                ResolveUrlMethodName = "Href"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #7
0
        internal MvcRazorHost(ICodeTreeCache codeTreeCache, RazorPathNormalizer pathNormalizer)
            : base(new CSharpRazorCodeLanguage())
        {
            _pathNormalizer = pathNormalizer;
            _baseType       = BaseType;
            _codeTreeCache  = codeTreeCache;

            TagHelperDescriptorResolver = new TagHelperDescriptorResolver();
            DefaultBaseClass            = BaseType + "<" + DefaultModel + ">";
            DefaultNamespace            = "Asp";
            // Enable instrumentation by default to allow precompiled views to work with BrowserLink.
            EnableInstrumentation = true;
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Microsoft.AspNet.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection",
                generatedTagHelperContext: new GeneratedTagHelperContext
            {
                ExecutionContextTypeName      = typeof(TagHelperExecutionContext).FullName,
                ExecutionContextAddMethodName = nameof(TagHelperExecutionContext.Add),
                ExecutionContextAddTagHelperAttributeMethodName =
                    nameof(TagHelperExecutionContext.AddTagHelperAttribute),
                ExecutionContextAddHtmlAttributeMethodName = nameof(TagHelperExecutionContext.AddHtmlAttribute),
                ExecutionContextOutputPropertyName         = nameof(TagHelperExecutionContext.Output),

                RunnerTypeName           = typeof(TagHelperRunner).FullName,
                RunnerRunAsyncMethodName = nameof(TagHelperRunner.RunAsync),

                ScopeManagerTypeName        = typeof(TagHelperScopeManager).FullName,
                ScopeManagerBeginMethodName = nameof(TagHelperScopeManager.Begin),
                ScopeManagerEndMethodName   = nameof(TagHelperScopeManager.End),

                TagHelperContentTypeName = nameof(TagHelperContent),

                // Can't use nameof because RazorPage is not accessible here.
                CreateTagHelperMethodName            = "CreateTagHelper",
                StartTagHelperWritingScopeMethodName = "StartTagHelperWritingScope",
                EndTagHelperWritingScopeMethodName   = "EndTagHelperWritingScope",

                WriteTagHelperAsyncMethodName   = "WriteTagHelperAsync",
                WriteTagHelperToAsyncMethodName = "WriteTagHelperToAsync",

                // Can't use nameof because IHtmlHelper is (also) not accessible here.
                MarkAsHtmlEncodedMethodName = HtmlHelperPropertyName + ".Raw",
            })
            {
                ResolveUrlMethodName   = "Href",
                BeginContextMethodName = "BeginContext",
                EndContextMethodName   = "EndContext"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #8
0
        internal MvcRazorHost(Type basePageType)
            : base(new CSharpRazorCodeLanguage())
        {
            DefaultBaseClass      = basePageType == null ? DefaultBaseType : basePageType.FullName;
            DefaultNamespace      = "Wyam.Modules.Razor";
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Wyam.Modules.Razor.Microsoft.AspNet.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection",
                generatedTagHelperContext: null)
            {
                ResolveUrlMethodName   = "Href",
                BeginContextMethodName = "BeginContext",
                EndContextMethodName   = "EndContext"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #9
0
        public OpenRastaRazorHost(RazorCodeLanguage codeLanguage)
        {
            NamespaceImports.Add("System");
            NamespaceImports.Add("System.Collections.Generic");
            NamespaceImports.Add("System.IO");
            NamespaceImports.Add("System.Linq");
            NamespaceImports.Add("System.Net");
            NamespaceImports.Add("System.Web");
            //NamespaceImports.Add("System.Web.Helpers");
            NamespaceImports.Add("System.Web.Security");
            NamespaceImports.Add("System.Web.UI");
            NamespaceImports.Add("System.Web.WebPages");

            DefaultNamespace      = WebDefaultNamespace;
            GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                              GeneratedClassContext.DefaultWriteMethodName,
                                                              GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                              WriteToMethodName,
                                                              WriteLiteralToMethodName,
                                                              TemplateTypeName,
                                                              DefineSectionMethodName);
            DefaultBaseClass        = typeof(RazorViewBase <>).AssemblyQualifiedName;
            DefaultDebugCompilation = true;
            CodeLanguage            = codeLanguage;
        }
Example #10
0
        /// <summary>
        /// 初始化 <see cref="Razor"/> 对象的新实例。
        /// </summary>
        public Razor()
        {
            RazorTemplateEngine = new RazorTemplateEngine(new System.Web.Razor.RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                GeneratedClassContext = new System.Web.Razor.Generator.GeneratedClassContext(
                    System.Web.Razor.Generator.GeneratedClassContext.DefaultExecuteMethodName,
                    System.Web.Razor.Generator.GeneratedClassContext.DefaultWriteMethodName,
                    System.Web.Razor.Generator.GeneratedClassContext.DefaultWriteLiteralMethodName,
                    "WriteTo", "WriteLiteralTo", "System.Action<System.IO.TextWriter>", "DefineSection")
                {
                    ResolveUrlMethodName = "ResolveUrl"
                },
                DefaultBaseClass = "Xuld.RazorEngine.TemplateBase<object>"
            });
            NamespaceImports.Add("System");
            NamespaceImports.Add("System.Collections.Generic");
            NamespaceImports.Add("System.Linq");
            NamespaceImports.Add("Microsoft.CSharp");

            CodeDomProvider = new CSharpCodeProvider();

            _compilerParameters = new CompilerParameters {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize"
            };
        }
        private WebPageRazorHost()
        {
            NamespaceImports.Add("System");
            NamespaceImports.Add("System.Collections.Generic");
            NamespaceImports.Add("System.IO");
            NamespaceImports.Add("System.Linq");
            NamespaceImports.Add("System.Net");
            NamespaceImports.Add("System.Web");
            NamespaceImports.Add("System.Web.Helpers");
            NamespaceImports.Add("System.Web.Security");
            NamespaceImports.Add("System.Web.UI");
            NamespaceImports.Add("System.Web.WebPages");
            NamespaceImports.Add("System.Web.WebPages.Html");

            RegisterSpecialFile(ApplicationStartFileName, typeof(ApplicationStartPage));
            RegisterSpecialFile(PageStartFileName, typeof(StartPage));
            DefaultNamespace      = WebDefaultNamespace;
            GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                              GeneratedClassContext.DefaultWriteMethodName,
                                                              GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                              WriteToMethodName,
                                                              WriteLiteralToMethodName,
                                                              TemplateTypeName,
                                                              DefineSectionMethodName)
            {
                ResolveUrlMethodName = ResolveUrlMethodName
            };
            DefaultPageBaseClass    = PageBaseClass;
            DefaultDebugCompilation = true;
        }
Example #12
0
 public bool Equals(DataContextStack stack)
 {
     return(this == stack || hashCode == stack.hashCode &&
            DataContextType == stack.DataContextType &&
            NamespaceImports.SequenceEqual(stack.NamespaceImports) &&
            Parent.Equals(stack.Parent));
 }
Example #13
0
 private void GetRidOfNamespace(string ns)
 {
     Debug.Assert(NamespaceImports.Contains(ns), ns + " is not a default namespace anymore");
     if (NamespaceImports.Contains(ns))
     {
         NamespaceImports.Remove(ns);
     }
 }
Example #14
0
 public bool Equals(DataContextStack stack)
 {
     return(ReferenceEquals(this, stack) || hashCode == stack.hashCode &&
            DataContextType == stack.DataContextType &&
            NamespaceImports.SequenceEqual(stack.NamespaceImports) &&
            ExtensionParameters.SequenceEqual(stack.ExtensionParameters) &&
            Equals(Parent, stack.Parent));
 }
Example #15
0
        /// <summary>
        /// Initializes a new instance of <see cref="MvcRazorHost"/> using the specified <paramref name="fileSystem"/>.
        /// </summary>
        /// <param name="fileSystem">A <see cref="IFileSystem"/> rooted at the application base path.</param>
        public MvcRazorHost(IFileSystem fileSystem)
            : base(new CSharpRazorCodeLanguage())
        {
            _fileSystem = fileSystem;
            _baseType   = BaseType;

            TagHelperDescriptorResolver = new TagHelperDescriptorResolver();
            DefaultBaseClass            = BaseType + '<' + DefaultModel + '>';
            DefaultNamespace            = "Asp";
            // Enable instrumentation by default to allow precompiled views to work with BrowserLink.
            EnableInstrumentation = true;
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Microsoft.AspNet.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection",
                generatedTagHelperContext: new GeneratedTagHelperContext
            {
                ExecutionContextTypeName      = typeof(TagHelperExecutionContext).FullName,
                ExecutionContextAddMethodName = nameof(TagHelperExecutionContext.Add),
                ExecutionContextAddTagHelperAttributeMethodName =
                    nameof(TagHelperExecutionContext.AddTagHelperAttribute),
                ExecutionContextAddHtmlAttributeMethodName = nameof(TagHelperExecutionContext.AddHtmlAttribute),
                ExecutionContextOutputPropertyName         = nameof(TagHelperExecutionContext.Output),

                RunnerTypeName           = typeof(TagHelperRunner).FullName,
                RunnerRunAsyncMethodName = nameof(TagHelperRunner.RunAsync),

                ScopeManagerTypeName        = typeof(TagHelperScopeManager).FullName,
                ScopeManagerBeginMethodName = nameof(TagHelperScopeManager.Begin),
                ScopeManagerEndMethodName   = nameof(TagHelperScopeManager.End),

                OutputGenerateStartTagMethodName = nameof(TagHelperOutput.GenerateStartTag),
                OutputGenerateContentMethodName  = nameof(TagHelperOutput.GenerateContent),
                OutputGenerateEndTagMethodName   = nameof(TagHelperOutput.GenerateEndTag),

                // Can't use nameof because RazorPage is not accessible here.
                CreateTagHelperMethodName   = "CreateTagHelper",
                StartWritingScopeMethodName = "StartWritingScope",
                EndWritingScopeMethodName   = "EndWritingScope",
            })
            {
                ResolveUrlMethodName   = "Href",
                BeginContextMethodName = "BeginContext",
                EndContextMethodName   = "EndContext"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #16
0
        public RazorHost(IExecutionContext executionContext, IChunkTreeCache chunkTreeCache, ITagHelperDescriptorResolver resolver, IBasePageTypeProvider basePageTypeProvider) : base(chunkTreeCache, resolver)
        {
            DefaultBaseClass = basePageTypeProvider.BasePageType.FullName;
            DefaultInheritedChunks.OfType <SetBaseTypeChunk>().First().TypeName = DefaultBaseClass;  // The chunk is actually what injects the base name into the view
            EnableInstrumentation = false;

            // Add additional default namespaces from the execution context
            foreach (string ns in executionContext.Namespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #17
0
        public PreprocessedRazorHost(string fullPath) : base(RazorCodeLanguage.GetLanguageByExtension(".cshtml"))
        {
            if (fullPath == null)
            {
                throw new ArgumentNullException("fullPath");
            }

            FullPath          = fullPath;
            _codeDomProvider  = new Microsoft.CSharp.CSharpCodeProvider();
            DefaultNamespace  = "ASP";
            EnableLinePragmas = true;
            StaticHelpers     = true;

            GeneratedClassContext = new GeneratedClassContext(
                GeneratedClassContext.DefaultExecuteMethodName,
                GeneratedClassContext.DefaultWriteMethodName,
                GeneratedClassContext.DefaultWriteLiteralMethodName,
                "WriteTo",
                "WriteLiteralTo",
                "Action<System.IO.TextWriter>",
                "DefineSection",
                "BeginContext",
                "EndContext"
                )
            {
                ResolveUrlMethodName = "Href"
            };

            codeGeneratorOptions = new CodeGeneratorOptions {
                // HACK: we use true, even though razor uses false, to work around a mono bug where it omits the
                // line ending after "#line hidden", resulting in the unparseable "#line hiddenpublic"
                BlankLinesBetweenMembers = true,
                BracingStyle             = "C",
                // matches Razor built-in settings
                IndentString = String.Empty,
            };

            foreach (var import in defaultImports)
            {
                NamespaceImports.Add(import);
            }
        }
Example #18
0
        public RazorTemplatingHost([NotNull] Type baseType)
            : base(new CSharpRazorCodeLanguage())
        {
            DefaultBaseClass = baseType.FullName;

            //ToDo: Why Do I need templateTypeName? Do I need other parameters?
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "")
            {
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #19
0
        public RazorHost(IExecutionContext executionContext, IChunkTreeCache chunkTreeCache, ITagHelperDescriptorResolver resolver, IBasePageTypeProvider basePageTypeProvider) : base(chunkTreeCache, resolver)
        {
            // Remove the backtick from generic class names
            string baseClassName = basePageTypeProvider.BasePageType.FullName;
            int    tickIndex     = baseClassName.IndexOf('`');

            if (tickIndex > 0)
            {
                baseClassName = baseClassName.Substring(0, tickIndex);
            }

            DefaultBaseClass = basePageTypeProvider.BasePageType.IsGenericTypeDefinition ? $"{baseClassName}<{ChunkHelper.TModelToken}>" : baseClassName;
            DefaultInheritedChunks.OfType <SetBaseTypeChunk>().First().TypeName = DefaultBaseClass;  // The chunk is actually what injects the base name into the view
            EnableInstrumentation = false;

            // Add additional default namespaces from the execution context
            foreach (string ns in executionContext.Namespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #20
0
        public MvcRazorHost()
            : base(new CSharpRazorCodeLanguage())
        {
            DefaultBaseClass      = typeof(RazorView).FullName;
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "Execute",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Template",
                defineSectionMethodName: "DefineSection")
            {
                ResolveUrlMethodName = "Href"
            };

            foreach (var ns in _namespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #21
0
        internal MvcRazorHost(IChunkTreeCache chunkTreeCache, RazorPathNormalizer pathNormalizer)
            : base(new CSharpRazorCodeLanguage())
        {
            _pathNormalizer = pathNormalizer;
            _chunkTreeCache = chunkTreeCache;

            DefaultBaseClass = $"{BaseType}<{ChunkHelper.TModelToken}>";
            DefaultNamespace = "Asp";
            // Enable instrumentation by default to allow precompiled views to work with BrowserLink.
            EnableInstrumentation = true;
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Microsoft.AspNetCore.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection",
                generatedTagHelperContext: new GeneratedTagHelperContext
            {
                ExecutionContextTypeName      = typeof(TagHelperExecutionContext).FullName,
                ExecutionContextAddMethodName = nameof(TagHelperExecutionContext.Add),
                ExecutionContextAddTagHelperAttributeMethodName =
                    nameof(TagHelperExecutionContext.AddTagHelperAttribute),
                ExecutionContextAddHtmlAttributeMethodName          = nameof(TagHelperExecutionContext.AddHtmlAttribute),
                ExecutionContextAddMinimizedHtmlAttributeMethodName =
                    nameof(TagHelperExecutionContext.AddMinimizedHtmlAttribute),
                ExecutionContextOutputPropertyName = nameof(TagHelperExecutionContext.Output),

                RunnerTypeName           = typeof(TagHelperRunner).FullName,
                RunnerRunAsyncMethodName = nameof(TagHelperRunner.RunAsync),

                ScopeManagerTypeName        = typeof(TagHelperScopeManager).FullName,
                ScopeManagerBeginMethodName = nameof(TagHelperScopeManager.Begin),
                ScopeManagerEndMethodName   = nameof(TagHelperScopeManager.End),

                TagHelperContentTypeName = typeof(TagHelperContent).FullName,

                // Can't use nameof because RazorPage is not accessible here.
                CreateTagHelperMethodName = "CreateTagHelper",
                FormatInvalidIndexerAssignmentMethodName = "InvalidTagHelperIndexerAssignment",
                StartTagHelperWritingScopeMethodName     = "StartTagHelperWritingScope",
                EndTagHelperWritingScopeMethodName       = "EndTagHelperWritingScope",

                // Can't use nameof because IHtmlHelper is (also) not accessible here.
                MarkAsHtmlEncodedMethodName           = HtmlHelperPropertyName + ".Raw",
                BeginAddHtmlAttributeValuesMethodName = "BeginAddHtmlAttributeValues",
                EndAddHtmlAttributeValuesMethodName   = "EndAddHtmlAttributeValues",
                AddHtmlAttributeValueMethodName       = "AddHtmlAttributeValue",
                HtmlEncoderPropertyName = "HtmlEncoder",
                TagHelperContentGetContentMethodName            = nameof(TagHelperContent.GetContent),
                TagHelperOutputIsContentModifiedPropertyName    = nameof(TagHelperOutput.IsContentModified),
                TagHelperOutputContentPropertyName              = nameof(TagHelperOutput.Content),
                ExecutionContextSetOutputContentAsyncMethodName = nameof(TagHelperExecutionContext.SetOutputContentAsync),
            })
            {
                BeginContextMethodName = "BeginContext",
                EndContextMethodName   = "EndContext"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }
Example #22
0
 public MyRazorHost(string virtualPath, string physicalPath) : base(virtualPath, physicalPath)
 {
     NamespaceImports.Add("RazorDemoSpike.Infrastructure");
 }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string RenderPocoClass(bool notifyPropertysChanged = false)
        {
            var sb = new ConsoleStringBuilderInterlaced();

            if (GenerateConfigMethod)
            {
                NamespaceImports.Add(typeof(ConfigurationResolver <>).Namespace);
            }

            if (notifyPropertysChanged)
            {
                NamespaceImports.Add(typeof(INotifyPropertyChanged).Namespace);
                NamespaceImports.Add(typeof(CallerMemberNameAttribute).Namespace);
            }

            NamespaceImports.Add(typeof(EagarDataRecord).Namespace);
            NamespaceImports.Add(typeof(GeneratedCodeAttribute).Namespace);
            NamespaceImports.Add(typeof(DbCollection <>).Namespace);

            sb.AppendInterlacedLine("//------------------------------------------------------------------------------");
            sb.AppendInterlacedLine("// <auto-generated>");
            sb.AppendInterlacedLine("// This code was generated by a tool.");
            sb.AppendInterlacedLine("// Runtime Version:2.0.50727.42");
            sb.AppendInterlacedLine("// Changes to this file may cause incorrect behavior and will be lost if");
            sb.AppendInterlacedLine("// the code is regenerated.");
            sb.AppendInterlacedLine("// </auto-generated>");
            sb.AppendInterlacedLine("//------------------------------------------------------------------------------");


            foreach (var namespaceImport in NamespaceImports)
            {
                sb.AppendLine($"using {namespaceImport};");
            }

            sb.AppendLine();
            sb.AppendLine("namespace " + Namespace);
            sb.AppendLine("{");
            sb.Up();
            sb.AppendLine();
            foreach (var headerLine in CompilerHeader)
            {
                sb.AppendInterlacedLine($"//{headerLine}");
            }


            sb.AppendLine();
            if (!GenerateConfigMethod)
            {
                foreach (var attributeInfo in Attributes)
                {
                    attributeInfo.Render(sb);
                }
            }
            if (GeneratedCodeAttribute != null)
            {
                sb.AppendInterlacedLine(
                    $"[{nameof(GeneratedCodeAttribute)}(tool: \"{GeneratedCodeAttribute.Tool}\", version: \"{GeneratedCodeAttribute.Version}\")]");
            }

            sb.AppendInterlaced("public partial class " + ClassName);
            if (!string.IsNullOrWhiteSpace(Inherts) || notifyPropertysChanged)
            {
                sb.Append($": {Inherts}");
                if (notifyPropertysChanged)
                {
                    if (!string.IsNullOrWhiteSpace(Inherts))
                    {
                        sb.Append(", ");
                    }
                    sb.Append(nameof(INotifyPropertyChanged));
                }
            }

            sb.AppendLine();
            sb.AppendInterlacedLine("{");
            sb.Up();
            sb.AppendInterlacedLine($"public {ClassName}() {{}}");

            if (GenerateConstructor && !GenerateFactory)
            {
                var readerName = "reader";
                sb.AppendInterlacedLine($"public {ClassName}({nameof(EagarDataRecord)} {readerName}) ");
                sb.AppendInterlacedLine("{").Up();

                foreach (var propertyInfo in Properties)
                {
                    propertyInfo.RenderAssignment(sb, readerName, "this");
                }

                sb.Down().AppendInterlacedLine("}");
            }

            if (!IsSuperClass)
            {
                foreach (var propertyInfo in Properties)
                {
                    propertyInfo.RenderProperty(sb, GenerateConfigMethod, notifyPropertysChanged);
                }
            }

            if (GenerateFactory)
            {
                var readerName = "reader";
                sb.AppendInterlacedLine($"public static {ClassName} Factory({nameof(EagarDataRecord)} {readerName})");
                sb.AppendInterlacedLine("{").Up();
                var targetName = "super";
                sb.AppendInterlacedLine($"var {targetName} = new {ClassName}();");

                foreach (var propertyInfo in Properties)
                {
                    propertyInfo.RenderAssignment(sb, readerName, targetName);
                }

                sb.AppendInterlacedLine($"return {targetName};");

                sb.Down().AppendInterlacedLine("}");
            }

            if (GenerateConfigMethod)
            {
                var      configArgument = string.Format("ConfigurationResolver<{0}>", ClassName);
                var      configName     = "config";
                string[] eventNames     =
                {
                    "BeforeConfig()", "AfterConfig()", $"BeforeConfig({configArgument} {configName})",
                    $"AfterConfig({configArgument} {configName})"
                };

                foreach (var eventName in eventNames)
                {
                    sb.AppendInterlacedLine($"static partial void {eventName};");
                }

                sb.AppendInterlacedLine($"[{nameof(ConfigMehtodAttribute)}]");
                sb.AppendInterlacedLine($"public static void Configuration({configArgument} {configName})");
                sb.AppendInterlacedLine("{");
                sb.Up();
                sb.AppendInterlacedLine("BeforeConfig();");
                sb.AppendInterlacedLine($"BeforeConfig({configName});");

                if (!GenerateConstructor)
                {
                    sb.AppendInterlacedLine(
                        $"config.{nameof(ConfigurationResolver<object>.SetFactory)}" +
                        "(" +
                        $"{ClassName}.Factory, " +
                        "true" +
                        ");");
                }

                foreach (var propertyInfoAttribute in Attributes)
                {
                    sb.AppendInterlacedLine(
                        $"config.{nameof(ConfigurationResolver<object>.SetClassAttribute)}" +
                        "(" +
                        $"new {propertyInfoAttribute.Name}({propertyInfoAttribute.RenderAssignments()})" +
                        ");");
                }

                foreach (var propertyInfo in Properties)
                {
                    foreach (var propertyInfoAttribute in propertyInfo.Attributes)
                    {
                        sb.AppendInterlacedLine(
                            $"config.{nameof(ConfigurationResolver<object>.SetPropertyAttribute)}" +
                            "(" +
                            $"s => s.{propertyInfo.Name}" +
                            ", " +
                            $"new {propertyInfoAttribute.Name}({propertyInfoAttribute.RenderAssignments()})" +
                            ");");
                    }
                }

                sb.AppendInterlacedLine($"AfterConfig({configName});");
                sb.AppendInterlacedLine("AfterConfig();");

                sb.Down();
                sb.AppendInterlacedLine("}");
            }

            if (notifyPropertysChanged)
            {
                sb.AppendInterlacedLine($"#region {nameof(INotifyPropertyChanged)}");
                sb.AppendInterlacedLine(
                    $"public event {nameof(PropertyChangedEventHandler)} {nameof(INotifyPropertyChanged.PropertyChanged)};");
                sb.AppendInterlacedLine("");
                sb.AppendInterlacedLine("protected virtual void SendPropertyChanged([CallerMemberName] string propertyName = null)");
                sb.AppendInterlacedLine("{").Up();
                sb.AppendInterlacedLine("PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));");
                sb.Down().AppendInterlacedLine("}");
                sb.AppendInterlacedLine("");
                sb.AppendInterlacedLine("#endregion");
            }

            sb.Down();
            sb.AppendInterlacedLine("}");
            sb.Down();
            sb.AppendLine("}");
            using (var writer = new StringWriter())
            {
                sb.WriteToSteam(writer, wrapper => { }, () => { });
                var stringBuilder = writer.GetStringBuilder();
                return(stringBuilder.ToString());
            }
        }
Example #24
0
        /// <summary>
        /// Initialies LightRazorHost with a specified fileprovider
        /// </summary>
        public RazorLightHost(IFileProvider viewsFileProvider) : base(new CSharpRazorCodeLanguage())
        {
            this._viewsFileProvider = viewsFileProvider;

            DefaultClassName      = _defaultClassName;
            DefaultNamespace      = _defaultNamespace;
            DefaultBaseClass      = $"{BaseType}<{ChunkHelper.TModelToken}>";
            EnableInstrumentation = false;             //This should not be true, unsell you want your code to work :)
            GeneratedClassContext = new GeneratedClassContext(
                executeMethodName: "ExecuteAsync",
                writeMethodName: "Write",
                writeLiteralMethodName: "WriteLiteral",
                writeToMethodName: "WriteTo",
                writeLiteralToMethodName: "WriteLiteralTo",
                templateTypeName: "Microsoft.AspNetCore.Mvc.Razor.HelperResult",
                defineSectionMethodName: "DefineSection",
                generatedTagHelperContext: new GeneratedTagHelperContext
            {
                ExecutionContextTypeName      = typeof(TagHelperExecutionContext).FullName,
                ExecutionContextAddMethodName = nameof(TagHelperExecutionContext.Add),
                ExecutionContextAddTagHelperAttributeMethodName =
                    nameof(TagHelperExecutionContext.AddTagHelperAttribute),
                ExecutionContextAddHtmlAttributeMethodName = nameof(TagHelperExecutionContext.AddHtmlAttribute),
                ExecutionContextOutputPropertyName         = nameof(TagHelperExecutionContext.Output),

                RunnerTypeName           = typeof(TagHelperRunner).FullName,
                RunnerRunAsyncMethodName = nameof(TagHelperRunner.RunAsync),

                ScopeManagerTypeName        = typeof(TagHelperScopeManager).FullName,
                ScopeManagerBeginMethodName = nameof(TagHelperScopeManager.Begin),
                ScopeManagerEndMethodName   = nameof(TagHelperScopeManager.End),

                TagHelperContentTypeName = typeof(TagHelperContent).FullName,

                // Can't use nameof because RazorPage is not accessible here.
                CreateTagHelperMethodName = "CreateTagHelper",
                FormatInvalidIndexerAssignmentMethodName = "InvalidTagHelperIndexerAssignment",
                StartTagHelperWritingScopeMethodName     = "StartTagHelperWritingScope",
                EndTagHelperWritingScopeMethodName       = "EndTagHelperWritingScope",
                BeginWriteTagHelperAttributeMethodName   = "BeginWriteTagHelperAttribute",
                EndWriteTagHelperAttributeMethodName     = "EndWriteTagHelperAttribute",

                // Can't use nameof because IHtmlHelper is (also) not accessible here.
                MarkAsHtmlEncodedMethodName           = HtmlHelperPropertyName + ".Raw",
                BeginAddHtmlAttributeValuesMethodName = "BeginAddHtmlAttributeValues",
                EndAddHtmlAttributeValuesMethodName   = "EndAddHtmlAttributeValues",
                AddHtmlAttributeValueMethodName       = "AddHtmlAttributeValue",
                HtmlEncoderPropertyName = "HtmlEncoder",
                TagHelperContentGetContentMethodName            = nameof(TagHelperContent.GetContent),
                TagHelperOutputIsContentModifiedPropertyName    = nameof(TagHelperOutput.IsContentModified),
                TagHelperOutputContentPropertyName              = nameof(TagHelperOutput.Content),
                ExecutionContextSetOutputContentAsyncMethodName = nameof(TagHelperExecutionContext.SetOutputContentAsync),
                TagHelperAttributeValuePropertyName             = nameof(TagHelperAttribute.Value),
            })
            {
                BeginContextMethodName = "BeginContext",
                EndContextMethodName   = "EndContext"
            };

            foreach (var ns in _defaultNamespaces)
            {
                NamespaceImports.Add(ns);
            }
        }