コード例 #1
0
        public void TemplateService_CanSupportCustomActivator_WithUnity()
        {
#if RAZOR4
            Assert.Ignore("We need to add roslyn to generate custom constructors!");
#endif

            var container = new UnityContainer();
            container.RegisterType(typeof(ITextFormatter), typeof(ReverseTextFormatter));

            var config = new TemplateServiceConfiguration
                             {
                                 Activator = new UnityTemplateActivator(container),
                                 BaseTemplateType = typeof(CustomTemplateBase<>)
                             };

#pragma warning disable 0618 // Fine because we still want to test if
            using (var service = new TemplateService(config))
#pragma warning restore 0618 // Fine because we still want to test if
            {
                const string template = "<h1>Hello @Format(Model.Forename)</h1>";
                const string expected = "<h1>Hello ttaM</h1>";

                var model = new Person { Forename = "Matt" };
                string result = service.Parse(template, model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #2
0
        public void CodeInspector_SupportsAddingCustomInspector()
        {
            var config = new TemplateServiceConfiguration();
            config.CodeInspectors.Add(new ThrowExceptionCodeInspector());

            using (var service = new TemplateService(config))
            {
                const string template = "Hello World";

                Assert.Throws<InvalidOperationException>(() => service.Parse(template));
            }
        }
コード例 #3
0
        public void RazorEngineHost_SupportsModelSpan_WithBaseType_NotGeneric_UsingCSharpCodeParser()
        {
            var config = new TemplateServiceConfiguration();
            config.BaseTemplateType = typeof(TemplateBase);
            using (var service = new TemplateService(config))
            {
                const string template = "@model RazorEngine.Tests.TestTypes.Person\[email protected]";
                const string expected = "Matt";

                var model = new Person {Forename = "Matt"};
                string result = service.Parse(template, (object)model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #4
0
        protected override string RenderTemplate(string content, PageContext pageData)
        {
            var serviceConfiguration = new TemplateServiceConfiguration
            {
                TemplateManager          = new IncludesResolver(FileSystem, includesPath),
                BaseTemplateType         = typeof(ExtensibleTemplate <>),
                DisableTempFileLocking   = true,
                CachingProvider          = new DefaultCachingProvider(t => { }),
                ConfigureCompilerBuilder = builder => ModelDirective.Register(builder)
            };

            serviceConfiguration.Activator = new ExtensibleActivator(serviceConfiguration.Activator, Filters, _allTags);

            Engine.Razor = RazorEngineService.Create(serviceConfiguration);

            content = Regex.Replace(content, "<p>(@model .*?)</p>", "$1");

            var pageContent = pageData.Content;

            pageData.Content = pageData.FullContent;

            try
            {
                content          = Engine.Razor.RunCompile(content, pageData.Page.File, typeof(PageContext), pageData);
                pageData.Content = pageContent;
                return(content);
            }
            catch (FileNotFoundException e)
            {
                Tracing.Error(
                    $"Failed to render template for page '{pageData.Page.Id}' for reason '{e.GetType().FullName}: {e.Message}', falling back to direct content"
                    );
                Tracing.Error("\t-Missing File: " + e.FileName);
                Tracing.Error("\t-Log: " + e.FusionLog);
                Tracing.Debug(e.StackTrace);
                return(content);
            }
            catch (Exception e)
            {
                Tracing.Error(
                    $"Failed to render template for page '{pageData.Page.Id}' for reason '{e.GetType().FullName}: {e.Message}', falling back to direct content"
                    );
                Tracing.Debug(e.StackTrace);
                return(content);
            }
        }
コード例 #5
0
        static int Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                // Console.WriteLine( "Switching to secound AppDomain, for RazorEngine..." );
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
                // RazorEngine will cleanup.
                AppDomain.Unload(domain);
                return(exitCode);
            }

            var filenameInputJson = "sample/defines.json";
            var defineJsonText    = File.ReadAllText(filenameInputJson);
            var defines           = DynamicJson.Parse(defineJsonText);

            var config = new TemplateServiceConfiguration
            {
                Debug = true,
                EncodedStringFactory = new RawStringFactory()                           // 出力で HTML エンコードを行わない '>' '<' などをそのまま出力する。デフォルトでは html エンコード '>' -> '&gt;' として出力される
            };

            var service = RazorEngineService.Create(config);
            var result  = "";

            string templateFile = "sample/sample.cshtml";
            var    template     = new LoadedTemplateSource(File.ReadAllText(templateFile), templateFile);

            result =
                service.RunCompile(template, "templateKey1", typeof(DynamicObject), ( object )defines);


            Console.WriteLine(result);

            return(0);
        }
コード例 #6
0
        public void TemplateService_CanParseTildeInTemplate_UsingRawEncoding()
        {
            var config = new TemplateServiceConfiguration()
            {
                EncodedStringFactory = new RawStringFactory()
            };

            using (var service = new TemplateService(config)) {
                const string template = "<a href=\"~/index.html\">@Model.String</a>";
                const string expected = "<a href=\"/index.html\">Matt</a>";

                var    model  = new { String = "Matt" };
                string result = service.Parse(template, model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #7
0
        public void TemplateService_CanPrecompileTemplate_WithNoModelAndANonGenericBase()
        {
            var config = new TemplateServiceConfiguration {
                BaseTemplateType = typeof(NonGenericTemplateBase)
            };

            using (var service = new TemplateService(config))
            {
                const string template = "<h1>@GetHelloWorldText()</h1>";
                const string expected = "<h1>Hello World</h1>";

                service.Compile(template, null, "test");

                string result = service.Run("test", null, null);
                Assert.That(result == expected, "Result does not match expected.");
            }
        }
コード例 #8
0
        public void StartNewRazorEngine()
        {
            var config = new TemplateServiceConfiguration();

#if DEBUG
            config.Debug = true;
#endif
            config.Namespaces.Add("Orchard");
            config.Namespaces.Add("Orchard.ContentManagement");
            config.Namespaces.Add("Orchard.Caching");
            //config.Namespaces.Add("System.Web.Helpers");
            config.ReferenceResolver = new MyIReferenceResolver();

            _razorEngine = RazorEngineService.Create(config);
            listOldCached.AddRange(listCached);
            listCached = new List <string>();
        }
コード例 #9
0
        public RazorMailMessageFactory(ITemplateResolver templateResolver, Type templateBase, Func <Type, object> dependencyResolver, ITemplateCache templateCache)
        {
            if (templateResolver == null)
            {
                throw new ArgumentNullException("templateResolver");
            }
            if (templateCache == null)
            {
                throw new ArgumentNullException("templateCache");
            }
            if (templateBase == null)
            {
                throw new ArgumentNullException("templateBase");
            }

            _templateResolver = templateResolver;
            _templateCache    = templateCache;

            var templateServiceConfiguration = new TemplateServiceConfiguration
            {
                // Layout resolver for razor engine
                // Once resolved, the layout will be cached by the razor engine, so the resolver is called only once during the lifetime of this factory
                // However, we want the ability to cache the layout even when the factory is instatiated multiple times
                Resolver = new DelegateTemplateResolver(layoutName =>
                {
                    var layout = _templateCache.Get(layoutName);

                    if (layout == null)
                    {
                        layout = _templateResolver.ResolveLayout(layoutName);
                        _templateCache.Add(layoutName, layout);
                    }
                    return(layout);
                }),

                // Set view base class
                BaseTemplateType = templateBase
            };

            if (dependencyResolver != null)
            {
                templateServiceConfiguration.Activator = new Activators.Activator(dependencyResolver);
            }

            _templateService = new TemplateService(templateServiceConfiguration);
        }
コード例 #10
0
        public RazorEngine()
        {
            var emailLayoutTemplate = GetManifestResource("Finastra.Hackathon.Emails.Templates.EmailLayout.cshtml");
            var pdfLayoutTemplate   = GetManifestResource("Finastra.Hackathon.Reports.Templates.ReportLayout.cshtml");

            var config = new TemplateServiceConfiguration()
            {
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { _cachedFilePaths.Add(t); }),
                EncodedStringFactory   = new RawStringFactory()
            };

            RazorEngineService = global::RazorEngine.Templating.RazorEngineService.Create(config);

            RazorEngineService.AddTemplate("EmailLayout", emailLayoutTemplate);
            RazorEngineService.AddTemplate("ReportLayout", pdfLayoutTemplate);
        }
コード例 #11
0
        public async Task <ActionResult> ChangeStatus(FormCollection form, ChangeStatusViewModel model)
        {
            try
            {
                orderProvider.SetStatusOrder(model.OrderId, model.NewStatusId, model.Notes, model.SendMail);
                if (model.SendMail)
                {
                    var order       = orderProvider.GetOrder(model.OrderId);
                    var orderStatus = orderStatusProvider.GetOrderStatus(model.NewStatusId);
                    var viewModel   = orderProvider.GetOrderMail(order);

                    if (orderStatus != null)
                    {
                        var config = new TemplateServiceConfiguration();
                        using (var service = RazorEngineService.Create(config))
                        {
                            var body = service.RunCompile(
                                orderStatus.EmailTemplate,
                                "OrderMail",
                                typeof(OrderMailViewModel),
                                new { viewModel });
                            await orderProvider.NotifyOrderStatusUpdate(
                                ConfigurationInstance[ConfigurationKeys.SmtpServer],
                                Convert.ToInt32(ConfigurationInstance[ConfigurationKeys.SmtpPort]),
                                Convert.ToBoolean(ConfigurationInstance[ConfigurationKeys.SmtpSsl]),
                                !Convert.ToBoolean(ConfigurationInstance[ConfigurationKeys.SmtpAuthentication]),
                                ConfigurationInstance[ConfigurationKeys.SmtpUserName],
                                ConfigurationInstance[ConfigurationKeys.SmtpPassword],
                                ConfigurationInstance[ConfigurationKeys.SystemSenderName],
                                ConfigurationInstance[ConfigurationKeys.SystemSenderAddress],
                                viewModel.CustomerMail,
                                body);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 406;
                Response.Write(ex.Message);
                return(null);
            }

            return(Json(model));
        }
コード例 #12
0
        public static String RazorRender(Object info, String razorTempl, String templateKey, Boolean debugMode = false)
        {
            var service = (IRazorEngineService)HttpContext.Current.Application.Get("NBrightDNNIRazorEngineService");

            if (service == null || debugMode)
            {
                // do razor test
                var config = new TemplateServiceConfiguration();
                config.Debug            = debugMode;
                config.BaseTemplateType = typeof(RazorEngineTokens <>);
                service = RazorEngineService.Create(config);
                HttpContext.Current.Application.Set("NBrightDNNIRazorEngineService", service);
            }
            Engine.Razor = service;
            var result = Engine.Razor.RunCompile(razorTempl, templateKey, null, info);

            return(result);
        }
コード例 #13
0
        public void TemplateService_CanParseSimpleHelperTemplate_UsingRawEncoding()
        {
            var config = new TemplateServiceConfiguration()
            {
                EncodedStringFactory = new RawStringFactory()
            };

            using (var service = new TemplateService(config))
            {
                const string template = "<h1>Hello @NameHelper()</h1>@helper NameHelper() { @Model.String }";
                const string expected = "<h1>Hello Matt & World</h1>";

                var    model  = new { String = "Matt & World" };
                string result = service.Parse(template, model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #14
0
        /// <summary>
        /// Constructs a RazorMailerEngine instance responsible for converting Razor templates into either a MailMessage or string.
        /// <para /> N.B. As this class loads up templates from the file system, it should only be created once per instance of your application.
        /// </summary>
        /// <param name="templatePath">The path to load the Razor templates from.  e.g. @"email\templates".  The template's Build Action should be set to Content and the Copy to Output Directory flag set to Copy Always</param>
        /// <param name="fromEmail">The address the email is from. e.g. [email protected]</param>
        /// <param name="fromName">The name the email is from. e.g. Your Site</param>
        /// <param name="dispatcher">The method by which to send the email.  Custom dispatchers can be implemented using the IEmailDispatcher interface</param>
        public RazorMailerEngine(string templatePath, string fromEmail, string fromName, IEmailDispatcher dispatcher)
        {
            _fromName   = fromName;
            _fromEmail  = fromEmail;
            _dispatcher = dispatcher;

            // Find templates in a web application
            var webPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", templatePath);
            // Find templates from a unit test or console application
            var libraryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templatePath);

            var config = new TemplateServiceConfiguration
            {
                TemplateManager = new ResolvePathTemplateManager(new[] { webPath, libraryPath })
            };

            _service = RazorEngineService.Create(config);
        }
コード例 #15
0
        public void TemplateRunner_CanRunTemplateString()
        {
            const string template = "Hello @Model.Forename, welcome to RazorEngine!";

            var configuration = new TemplateServiceConfiguration {
                Debug = true
            };

            using (var service = RazorEngineService.Create(configuration))
            {
                var runner = service.CompileRunner <Person>(template);
                var output = runner.Run(new Person {
                    Forename = "Max"
                });

                Assert.AreEqual("Hello Max, welcome to RazorEngine!", output);
            }
        }
コード例 #16
0
ファイル: RazorTemplate.cs プロジェクト: hanifhn/Qowaiv
        public void GenerateFile(T model, FileInfo targetLocation)
        {
            var config = new TemplateServiceConfiguration
            {
                Language             = Language.CSharp,
                Debug                = true,
                EncodedStringFactory = new RawStringFactory()
            };

            var service = RazorEngineService.Create(config);

            using (var writer = new StreamWriter(targetLocation.FullName, true))
            {
                var result = service.RunCompile(data, ClassName, typeof(T), model);
                writer.Write(result);
                writer.Flush();
            }
        }
コード例 #17
0
    public static void Configure()
    {
        var templateConfig = new TemplateServiceConfiguration
        {
            Resolver = new DelegateTemplateResolver(name =>
            {
                //no caching cause RazorEngine handles that itself
                var emailsTemplatesFolder = HttpContext.Current.Server.MapPath(Properties.Settings.Default.EmailTemplatesLocation);
                var templatePath          = Path.Combine(emailsTemplatesFolder, name);
                using (var reader = new StreamReader(templatePath))                                         // let it throw if doesn't exist
                {
                    return(reader.ReadToEnd());
                }
            })
        };

        RazorEngine.Razor.SetTemplateService(new TemplateService(templateConfig));
    }
コード例 #18
0
        public void RazorEngineHost_SupportsModelSpan_WithBaseType_NotGeneric_UsingCSharpCodeParser()
        {
            var config = new TemplateServiceConfiguration();

            config.BaseTemplateType = typeof(TemplateBase);
            using (var service = new TemplateService(config))
            {
                const string template = "@model RazorEngine.Tests.TestTypes.Person\[email protected]";
                const string expected = "Matt";

                var model = new Person {
                    Forename = "Matt"
                };
                string result = service.Parse(template, (object)model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #19
0
        public void RazorEngineHost_SupportsModelSpan_UsingVBCodeParser()
        {
            var config = new TemplateServiceConfiguration
                             {
                                 Language = Language.VisualBasic
                             };

            using (var service = new TemplateService(config))
            {
                const string template = "@ModelType List(Of RazorEngine.Tests.TestTypes.Person)\[email protected]";
                const string expected = "1";

                var model = new List<Person> { new Person() { Forename = "Matt", Age = 27 } };
                string result = service.Parse(template, (object)model);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #20
0
        static void Main(string[] args)
        {
            string template = "Hello @Model.Name, welcome to RazorEngine!";
            var    result   = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });

            Console.WriteLine(result);

            string templateFilePath   = "HelloWorld.cshtml";
            var    templateFile       = File.ReadAllText(templateFilePath);
            string templateFileResult = Engine.Razor.RunCompile(templateFile, Guid.NewGuid().ToString(), null, new
            {
                Name = "World"
            });

            Console.WriteLine(templateFileResult);

            string copyRightTemplatePath = "CopyRightTemplate.cshtml";
            var    copyRightTemplate     = File.ReadAllText(copyRightTemplatePath);
            string copyRightResult       = Engine.Razor.RunCompile(copyRightTemplate, Guid.NewGuid().ToString(), typeof(CopyRightUserInfo), new CopyRightUserInfo
            {
                CreateTime   = DateTime.Now,
                EmailAddress = "*****@*****.**",
                UserName     = "******"
            });

            Console.WriteLine(copyRightResult);

            ITemplateServiceConfiguration configuration = new TemplateServiceConfiguration()
            {
                Language             = Language.CSharp,
                EncodedStringFactory = new RawStringFactory(),
                Debug = true
            };

            configuration.Namespaces.Add("Helpers");

            IRazorEngineService service = RazorEngineService.Create(configuration);

            string template2 = @"Hello @Model.Name, @TextHelper.Decorate(Model.Name)";
            string result2   = service.RunCompile(template2, "templateKey", null, new { Name = "World" });

            Console.WriteLine(result2);
            Console.ReadKey();
        }
コード例 #21
0
        public void CreateJsProxy(List <Type> svTypes, List <Type> itTypes)
        {
            if (svTypes == null || svTypes.Count == 0)
            {
                return;
            }
            var config = new TemplateServiceConfiguration {
                EncodedStringFactory = new RawStringFactory()
            };
            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
            var template = ReadTemplate("Angular_Proxy_tmp.cshtml");
            var model    = Build(svTypes, itTypes);
            var result   = Engine.Razor.RunCompile(template, "Services", typeof(List <ServiceWithMethod>), model);
            var savePath = AppPath.GetFullDirByRelativeDir(Config.OutputRelativePath);

            File.WriteAllText(savePath + "mabp.service.ts", result, System.Text.Encoding.UTF8);
        }
コード例 #22
0
ファイル: Order.cs プロジェクト: chuckconway/bike-distributor
        private static string CompileTemplate(Receipt model, string resourceName, string templateKey)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var template = string.Empty;

            using (var stream = assembly.GetManifestResourceStream(resourceName))
                using (var reader = new StreamReader(stream))
                {
                    template = reader.ReadToEnd();
                }

            var config = new TemplateServiceConfiguration {
                EncodedStringFactory = new RawStringFactory()
            };

            Engine.Razor = RazorEngineService.Create(config);

            return(Engine.Razor.RunCompile(template, templateKey, null, model));
        }
コード例 #23
0
        internal void InitializeRazor()
        {
            if (_initialized)
            {
                return;
            }

            TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration
            {
                DisableTempFileLocking = true,
                EncodedStringFactory   = new RawStringFactory(),
                CachingProvider        = new DefaultCachingProvider(x => { })
            };
            var service = RazorEngineService.Create(templateConfig);

            Engine.Razor = service;

            _initialized = true;
        }
コード例 #24
0
ファイル: GridGenerator.cs プロジェクト: wxhjiy/JqGridForMvc
        /// <summary>
        ///     表格生成器
        /// </summary>
        /// <returns></returns>
        public string ToHtmlString()
        {
            var cacheValue = GridConfiguration.PerClearCache ? null : CacheHelper.Get("JqGird_Config_" + _gridId);

            if (cacheValue != null)
            {
                return(cacheValue.ToString());
            }//
            string template    = @"
              <!--该表格由HalwerHub.JqGrid自动生成,联系QQ:121625933-->
              <table id='@Model.GridId'></table> 
              <div id ='@Model.PagerId'></div >
              <script type='text/javascript'>
                jQuery(function(){
                @Model.TableInitCommand
                @Model.BottomNavBarInitCommand
                @Model.GroupHeaderInitCommand
                @Model.MergerColumnInitCommand
              });   
            </script>";
            var    initCommand = new RenderInitCommand();

            initCommand.GridId = _gridId;
            initCommand.GroupHeaderInitCommand = GridConfiguration.GroupHeaders? "jQuery('#" + _gridId + "').jqGrid('setGroupHeaders'," + GridConfiguration.ColSPanConfiguation.IgnoreNullSerialize() + ")": "";
            initCommand.TableInitCommand       = "jQuery('#" + _gridId + "').jqGrid(" + GridConfiguration.IgnoreNullSerialize() + ")";
            initCommand.PagerId = GridConfiguration.PagerId?.Substring(1);
            var colNames = GridConfiguration.GridColumns.Where(col => col.CellAttr != null).ToList();

            if (colNames.Any())
            {
                GridConfiguration.GridComplete      = @"&function() {" + colNames.Aggregate("", (current, col) => current + ("Merger(\'" + _gridId + "\', \'" + col.Field + "\');")) + "}&";
                initCommand.MergerColumnInitCommand = "function Merger(gridName, cellName) { var mya = $('#' + gridName + '').getDataIDs(); var length = mya.length;for (var i = 0; i < length; i++){ var before = $('#' + gridName + '').jqGrid('getRowData', mya[i]); var rowSpanTaxCount = 1; for (j = i + 1; j <= length; j++) { var end = $('#' + gridName + '').jqGrid('getRowData', mya[j]); if (before[cellName] == end[cellName]) { rowSpanTaxCount++;$('#' + gridName + '').setCell(mya[j], cellName, '', { display: 'none' }); } else { rowSpanTaxCount = 1; break; }$('td[aria-describedby=' + gridName +'_' + cellName +']', '#' + gridName +'').eq(i).attr('rowspan', rowSpanTaxCount);}}};";
            }
            initCommand.BottomNavBarInitCommand = "$('#" + _gridId + "').jqGrid( 'navGrid' ,  '#" + initCommand.PagerId + "'," + GridConfiguration.GridOperation.IgnoreNullSerialize() + ",{},{},{},{" + (GridConfiguration.MultiSearch ? "multipleSearch:true" : "") + "},{});";
            var config = new TemplateServiceConfiguration {
                EncodedStringFactory = new RawStringFactory()
            };
            var service = RazorEngineService.Create(config);
            var result  = service.RunCompile(template, "templateKey", typeof(RenderInitCommand), initCommand);

            CacheHelper.Add("JqGird_Config_" + _gridId, result, 5);
            return(result.Replace("\"&", "").Replace("&\"", "").Replace("\\", ""));
        }
コード例 #25
0
ファイル: RazorRenderer.cs プロジェクト: lililililil/tinysite
        public RazorRenderer()
        {
            this.TopLevelTemplates = new Dictionary <string, LoadedTemplateSource>();

            var manager = new TemplateManager();

            manager.TopLevelTemplates = this.TopLevelTemplates;

            var config = new TemplateServiceConfiguration();

            config.AllowMissingPropertiesOnDynamic = true;
            config.Namespaces.Add("System.IO");
            config.Namespaces.Add("RazorEngine.Text");
            config.TemplateManager = manager;

            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
        }
コード例 #26
0
ファイル: TemplateManager.cs プロジェクト: goupviet/MiniAbp
        public static void GenerateProxyJs(List <Type> svTypes, List <Type> itTypes)
        {
            if (svTypes == null || svTypes.Count == 0)
            {
                return;
            }
            var config = new TemplateServiceConfiguration {
                EncodedStringFactory = new RawStringFactory()
            };
            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
            var template = ReadTemplate("ServicesTemplate.cshtml");
            var model    = Build(svTypes, itTypes);
            var result   = Engine.Razor.RunCompile(template, "Services", typeof(List <ServiceWithMethod>), model);
            var savePath = AppPath.GetRelativeDir("Content\\Lib\\miniAbp\\auto\\");

            File.WriteAllText(savePath + "mabpProxy.js", result, Encoding.UTF8);
        }
コード例 #27
0
ファイル: EzCMSConfig.cs プロジェクト: levanvunam/EasyCMS
        /// <summary>
        /// Register the view engine for application
        /// </summary>
        public static void RegisterViewEngine()
        {
            //Remove all engines
            ViewEngines.Engines.Clear();

            #region RazorEngine

            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType     = typeof(RazorEngineTemplateBase <>),
                EncodedStringFactory = new RazorEngineMvcHtmlStringFactory(),
                TemplateManager      = new RazorEngineTemplateManager(),
                Debug = false
            };

            #region Namespaces

            var webConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web.config");
            var fileMap       = new ExeConfigurationFileMap {
                ExeConfigFilename = webConfigPath
            };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var razorConfig   = configuration.GetSection("system.web/pages") as PagesSection;

            if (razorConfig != null)
            {
                foreach (NamespaceInfo namespaceInfo in razorConfig.Namespaces)
                {
                    config.Namespaces.Add(namespaceInfo.Namespace);
                }
            }

            #endregion

            Engine.Razor = RazorEngineService.Create(config);

            #endregion

            //Add Razor Engine
            ViewEngines.Engines.Add(new EzCMSRazorEngine());

            HostingEnvironment.RegisterVirtualPathProvider(new EzCMSVirtualPathProvider());
        }
コード例 #28
0
        public RazorMessageGenerator(ITemplateLocator templateLocator)
        {
            if (templateLocator == null)
            {
                throw new ArgumentNullException("templateLocator");
            }

            _templateLocator = templateLocator;

            var serviceConfiguration = new TemplateServiceConfiguration
            {
                BaseTemplateType = typeof(MessageTemplate <>),
                Namespaces       = new HashSet <string> {
                    typeof(MessageTemplate <>).Namespace
                }
            };

            _service = new TemplateService(serviceConfiguration);
        }
コード例 #29
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            string        excelFilename       = args[0];
            string        emailConfigFilename = args[1];
            EmailConfig   eConfig             = GetConfig(emailConfigFilename);
            BirthdayModel birthdays           = new BirthdayModel(ContactBuilder.ReadExcel(excelFilename), DateTime.Today);

            if (birthdays.Contacts.Count() == 0)
            {
                return;
            }
            var tConfig = new TemplateServiceConfiguration()
            {
                DisableTempFileLocking = true,
                TemplateManager        = new ResolvePathTemplateManager(new string[] { AppDomain.CurrentDomain.BaseDirectory }),
                CachingProvider        = new DefaultCachingProvider(t => { }),
            };

            using (var service = RazorEngineService.Create(tConfig)) {
                service.Compile("MonthlyBirthdays", typeof(BirthdayModel));
                string template = service.Run("MonthlyBirthdays", modelType: typeof(BirthdayModel), model: birthdays);
                using (SmtpClient client = new SmtpClient()
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = eConfig.Authentication.AsCredential()
                }) {
                    using (var message = new MailMessage(eConfig.Envelope.From.AsAddress(), eConfig.Envelope.To.AsAddress())
                    {
                        Subject = String.Format("{0:MMMM} Birthdays", birthdays.Month),
                        IsBodyHtml = true,
                        Body = template
                    }) {
                        message.Bcc.Add(eConfig.Envelope.Self.AsAddress());
                        client.Send(message);
                    }
                }
            }
        }
コード例 #30
0
        public void init(Type rootPage = null, IEnumerable <string> layoutRoots = null, Assembly assembly = null)
        {
            if (layoutRoots == null)
            {
                layoutRoots = new string[] { HttpRuntime.AppDomainAppPath }
            }
            ;

            TemplateServiceConfiguration razorConfig = new TemplateServiceConfiguration()
            {
                Debug            = debugMode,
                BaseTemplateType = typeof(WebMetalTemplate <>)
            };

            razorConfig.TemplateManager = new WebMetalResolvePathTemplateManager(layoutRoots);
            razorConfig.CachingProvider = new WebMetalCachingProvider()
            {
                application = this
            };

            razorService = RazorEngineService.Create(razorConfig);

            if (assembly == null)
            {
                assembly = Assembly.GetCallingAssembly();
            }

            if (rootPage != null)
            {
                addPage(rootPage, "");
            }

            foreach (Type type in assembly.GetTypes())
            {
                if (type.IsSubclassOf(typeof(Page)) && !type.FullName.StartsWith("webmetal") && type.GetCustomAttribute <Ignore>() == null)
                {
                    addPage(type, getName(type));
                }
            }

            mimeTypeHandlers.Add("text/plain", new TextPlainMimeTypeHandler());
        }
コード例 #31
0
        public string Format(ReportTemplate template, Type[] interfaceTypes)
        {
            var accessorTypeBuilder = new AccessorTypeBuilder();

            var interfaceReportDataCollection = interfaceTypes
                                                .Select(_ => accessorTypeBuilder.Parse(_))
                                                .Select(CreateReportData).ToArray();

            var reportData = new ReportData(interfaceReportDataCollection, _propertyFormatters);

            var tempFolders = new List <string>();

            try
            {
                // https://github.com/Antaris/RazorEngine/issues/244
                var config = new TemplateServiceConfiguration
                {
                    DisableTempFileLocking = true,
                    CachingProvider        = new DefaultCachingProvider(t =>
                    {
                        tempFolders.Add(t);
                    })
                };
                RazorEngine.Engine.Razor = RazorEngineService.Create(config);
                return(RazorEngine.Engine.Razor.RunCompile(template.TemplateRawText, "templateKey", typeof(ReportData),
                                                           reportData));
            }
            finally
            {
                foreach (var folder in tempFolders)
                {
                    try
                    {
                        Directory.Delete(folder, true);
                    }
                    catch
                    {
                        _logWriter.WriteLine($"Failed to delete temporary folder:{folder}");
                    }
                }
            }
        }
コード例 #32
0
        // <summary>
        /// 解析模板生成静态页
        /// </summary>
        /// <param name="temp">模板地址</param>
        /// <param name="path">静态页地址</param>
        /// <param name="t">数据模型</param>
        /// <returns></returns>
        public bool CreateStaticPage(string temp, string path, TempModel t)
        {
            try
            {
                //实例化模型


                var config = new TemplateServiceConfiguration();
                using (var service = RazorEngineService.Create(config))
                {
                    var    model  = t;
                    string result = service.RunCompile(temp, string.Empty, null, model);
                    return(CreateFileHtmlByTemp(result, path));
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #33
0
        public static void SendExceptionEmail(ExceptionEmailClass exceptionEmailClass)
        {
            try
            {
                var config = new TemplateServiceConfiguration
                {
                    TemplateManager        = new ResolvePathTemplateManager(new[] { "EmailTemplates" }),
                    DisableTempFileLocking = true
                };

                Engine.Razor = RazorEngineService.Create(config);
                var emailHtmlBody = Engine.Razor.RunCompile("ExceptionEmail.cshtml", null, exceptionEmailClass);

                SendFinal(emailHtmlBody, $"Exception occurred in Application {exceptionEmailClass.ExceptionSource}");
            }
            catch (Exception e)
            {
                Logger.Error($"Error Details: {e.Message}\r\nStack: {e.StackTrace}");
            }
        }
        private void ConfigureRazorEngine()
        {
            var config = new TemplateServiceConfiguration
            {
                // Disable temp file locking, since we don't expect much templates, they don't change at runtime and we trust them.
                // This allows RazorEngine to delete the files, without requiring us to run it in a separate AppDomain.
                // See https://antaris.github.io/RazorEngine/index.html#Temporary-files.
                DisableTempFileLocking = true,

                // Disable warnings that temp files cannot be cleaned up.
                CachingProvider = new DefaultCachingProvider(t => { }),

                // Use custom reference resolver to make it work with assemblies embedded through Costura.Fody.
                ReferenceResolver = new RazorEngineReferenceResolver(),
            };

            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
        }
コード例 #35
0
        public void TemplateService_CanSupportCustomActivator_WithUnity()
        {
            var container = new UnityContainer();
            container.RegisterType(typeof(ITextFormatter), typeof(ReverseTextFormatter));

            var config = new TemplateServiceConfiguration
                             {
                                 Activator = new UnityTemplateActivator(container),
                                 BaseTemplateType = typeof(CustomTemplateBase<>)
                             };

            using (var service = new TemplateService(config))
            {
                const string template = "<h1>Hello @Format(Model.Forename)</h1>";
                const string expected = "<h1>Hello ttaM</h1>";

                var model = new Person { Forename = "Matt" };
                string result = service.Parse(template, model);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #36
0
        public void RazorEngineHost_SupportsModelSpan_WithBaseType_NotGeneric_UsingVBCodeParser()
        {
            Assert.Ignore("Should this really work?");
            var config = new TemplateServiceConfiguration();
            config.BaseTemplateType = typeof(TemplateBase);
            config.Language = Language.VisualBasic;

            using (var service = new TemplateService(config))
            {
                const string template = "@ModelType List(Of RazorEngine.Tests.TestTypes.Person)\[email protected]";
                const string expected = "1";

                var model = new List<Person> { new Person() { Forename = "Matt", Age = 27 } };
                string result = service.Parse(template, (object)model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
コード例 #37
0
        public void TemplateService_CanParseSimpleTemplate_UsingRawEncoding()
        {
            var config = new TemplateServiceConfiguration()
            {
                EncodedStringFactory = new RawStringFactory()
            };

            using (var service = new TemplateService(config))
            {
                const string template = "<h1>Hello @Model.String</h1>";
                const string expected = "<h1>Hello Matt & World</h1>";

                var model = new { String = "Matt & World" };
                string result = service.Parse(template, model);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }