/// <param name="type">The type of the object to serialize.</param>
        /// <param name="value">The object value to write. Can be null.</param>
        /// <param name="writeStream">The stream to which to write.</param>
        /// <param name="content">The <see cref="T:System.Net.Http.HttpContent"/>, if available. Can be null.</param>
        public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
        {
            if (type != typeof(RazorContext))
            {
                throw new ArgumentOutOfRangeException("type");
            }
            if (writeStream == null)
            {
                throw new ArgumentNullException("writeStream");
            }

            RazorContext razorContext = value as RazorContext;

            if (razorContext == null)
            {
                throw new ArgumentException("value is not RazorContext");
            }

            Encoding encoding = SelectCharacterEncoding(content == null ? null : content.Headers);

            using (var isolatedRazor = IsolatedRazorEngineService.Create(razorContext.GetConfigCreator()))
                using (var writer = new StreamWriter(writeStream, encoding))
                {
                    string cacheKey = razorContext.RazorTemplate.GetHashCode().ToString("X8");
                    object model    = razorContext.Model;

                    isolatedRazor.RunCompile(razorContext.RazorTemplate, cacheKey, writer, null, model);
                    writer.Flush();
                }
        }
Esempio n. 2
0
 public RazorTemplatePaser(IParserConfig parseConfig)
 {
     config       = new TemplateServiceConfiguration();
     config.Debug = parseConfig.EnableDebug;
     //config.TemporaryDirectory
     config.Language = Language.CSharp;
     config.DisableTempFileLocking = true;//as well. This will work in any AppDomain (including the default one)
     if (config.Debug)
     {
         config.DisableTempFileLocking = false;
     }
     //config.CachingProvider = new DefaultCachingProvider(t => { });
     config.CachingProvider      = new DefaultCachingProvider();
     config.EncodedStringFactory = new RazorEngine.Text.RawStringFactory(); // Raw string encoding.
     config.ReferenceResolver    = new LocalReferenceResolver();
     //DelegateTemplateManager: (default) Used as the default for historical reasons, easy solution when using dynamic template razor strings.
     //ResolvePathTemplateManager: Used to resolve templates from a given list of directory paths. Doesn't support adding templates dynamically via string. You can use a full path instead of a template name.
     //EmbeddedResourceTemplateManager: Used to resolve templates from assembly embedded resources. Uses Assembly.GetManifestResourceStream(Type, string) to load the template based on the type provided.
     //WatchingResolvePathTemplateManager: Same as ResolvePathTemplateManager but watches the filesystem and invalidates the cache. Note that this introduces a memory leak to your application, so only use this is you have an AppDomain recycle strategy in place or for debugging purposes.
     templateManager        = new DelegateTemplateManager();
     config.TemplateManager = templateManager;
     //config.EncodedStringFactory = new RazorEngine.Text.HtmlEncodedStringFactory(); // Html encoding.
     if (parseConfig.EnableSandbox)
     {
         var service = IsolatedRazorEngineService.Create(new SandBoxConfigCreator(config), SandBox.SandboxCreator);
         Engine.Razor = service;
     }
     else
     {
         var service = RazorEngineService.Create(config);
         Engine.Razor = service;
     }
 }
            /// <summary>
            /// Check if everything is cleaned up.
            /// </summary>
            public void IsolatedRazorEngineService_CleanUpWorks()
            {
                var appDomain = SandboxCreator();

                using (var service = IsolatedRazorEngineService.Create(() => appDomain))
                {
                    string template = @"@Model.Name";

                    var result = service.RunCompile(template, "test", null, new { Name = "test" });
                    Assert.AreEqual("test", result);


                    ObjectHandle handle =
                        Activator.CreateInstanceFrom(
                            appDomain, typeof(AssemblyChecker).Assembly.ManifestModule.FullyQualifiedName,
                            typeof(AssemblyChecker).FullName
                            );

                    using (var localHelper = new AssemblyChecker())
                    {
                        Assert.False(localHelper.ExistsCompiledAssembly());
                    }
                    using (var remoteHelper = (AssemblyChecker)handle.Unwrap())
                    {
                        Assert.IsTrue(remoteHelper.ExistsCompiledAssembly());
                    }
                }
                Assert.Throws <AppDomainUnloadedException>(() => { Console.WriteLine(appDomain.FriendlyName); });
                using (var localHelper = new AssemblyChecker())
                {
                    Assert.False(localHelper.ExistsCompiledAssembly());
                }
            }
 public void IsolatedRazorEngineService_WillThrowException_WhenUsingNullAppDomain()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         using (var service = IsolatedRazorEngineService.Create(() => null))
         { }
     });
 }
Esempio n. 5
0
        public void IsolatedRazorEngineService_Sandbox_WithISerializableModel()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                const string template = "<h1>Uri Host: @Model.Host</h1>";
                const string expected = "<h1>Uri Host: example.com</h1>";

                var model  = new Uri("http://example.com");
                var result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
                Assert.AreEqual(expected, result);
            }
        }
Esempio n. 6
0
        public void IsolatedRazorEngineService_DynamicViewBag_FromSandBox()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                const string template = "@{ ViewBag.Test = \"TestItem\"; }";
                const string expected = "TestItem";
                dynamic      viewbag  = new DynamicViewBag();

                string result = service.RunCompile(template, "test", (Type)null, (object)null, (DynamicViewBag)viewbag);
                Assert.AreEqual(expected, viewbag.Test);
            }
        }
        public void IsolatedRazorEngineService_Sandbox_WithAnonymousModel()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                const string template = "<h1>Animal Type: @Model.Type</h1>";
                const string expected = "<h1>Animal Type: Cat</h1>";

                var model  = new { Type = "Cat" };
                var result = service.RunCompile(template, "test", null, new RazorDynamicObject(model));
                Assert.AreEqual(expected, result);
            }
        }
 public void IsolatedRazorEngineService_StaticModelDynamicType_InSandBox()
 {
     using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
     {
         const string template = "<h1>Hello @Model.Name</h1>";
         const string expected = "<h1>Hello Matt</h1>";
         // We "abuse" NameOnlyTemplateKey because it is SecurityTransparent and serializable.
         var    model  = new NameOnlyTemplateKey("Matt", ResolveType.Global, null);
         string result = service.RunCompile(template, "test", null, model);
         Assert.AreEqual(expected, result);
     }
 }
        public void IsolatedRazorEngineService_CanParseSimpleTemplate_WithNoModel()
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Hello World</h1>";
                const string expected = template;

                string result = service.RunCompile(template, "test");

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
 public void IsolatedRazorEngineService_Dynamic_InSandBox()
 {
     using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
     {
         const string template = "<h1>Hello @Model.Forename, @ViewBag.Test</h1>";
         const string expected = "<h1>Hello Matt, TestItem</h1>";
         dynamic      viewbag  = new DynamicViewBag();
         viewbag.Test     = "TestItem";
         viewbag.Forename = "Matt";
         string result = service.RunCompile(template, "test", null, (object)viewbag, (DynamicViewBag)viewbag);
         Assert.AreEqual(expected, result);
     }
 }
        public void IsolatedRazorEngineService_ParseSimpleTemplate_WithExpandoModel()
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Animal Type: @Model.Type</h1>";
                const string expected = "<h1>Animal Type: Cat</h1>";

                dynamic model = new ExpandoObject();
                model.Type = "Cat";
                var result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
                Assert.AreEqual(expected, result);
            }
        }
        public void IsolatedRazorEngineService_StaticSecurityCriticalModelWrapped_InSandbox()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                const string template = "<h1>Hello World @Model.Forename</h1>";
                const string expected = "<h1>Hello World TestForename</h1>";
                var          model    = new Person {
                    Forename = "TestForename"
                };

                string result = service.RunCompile(template, "test", null, new RazorDynamicObject(model));
                Assert.AreEqual(expected, result);
            }
        }
        public void IsolatedRazorEngineService_CannotParseSimpleTemplate_WithDynamicModel()
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Animal Type: @Model.Type</h1>";
                const string expected = "<h1>Animal Type: Cat</h1>";

                dynamic model = new ValueObject(new Dictionary <string, object> {
                    { "Type", "Cat" }
                });
                string result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
                Assert.AreEqual(expected, result);
            }
        }
        public void IsolatedRazorEngineService_CanParseSimpleTemplate_WithComplexSerializableModel()
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Hello @Model.Forename</h1>";
                const string expected = "<h1>Hello Matt</h1>";

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

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void IsolatedRazorEngineService_CannotParseSimpleTemplate_WithComplexNonSerializableModel()
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Animal Type: @Model.Type</h1>";

                Assert.Throws <SerializationException>(() =>
                {
                    var model = new Animal {
                        Type = "Cat"
                    };
                    service.RunCompile(template, "test", typeof(Animal), model);
                });
            }
        }
Esempio n. 16
0
        public void IsolatedRazorEngineService_WillThrowException_WhenUsingDisableFileLocking()
        {
            Assert.Throws <InvalidOperationException>(() =>
            {
                using (var service = IsolatedRazorEngineService.Create(new InsecureConfigCreator(), SandboxCreator))
                {
                    const string template = "<h1>Hello World</h1>";
                    const string expected = template;

                    string result = service.RunCompile(template, "test");

                    Assert.That(result == expected, "Result does not match expected: " + result);
                }
            });
        }
Esempio n. 17
0
        public string MakeConfigurationFile(string outputPath = null)
        {
            // https://github.com/Antaris/RazorEngine/issues/244
            using (var service = IsolatedRazorEngineService.Create(AppdomainHelper.SandboxCreator))
            {
                var contents = service.RunCompile(_templateContent, "nginx.configuration", typeof(INginxConfiguration), _configuration);

                if (outputPath != null)
                {
                    File.WriteAllText(outputPath, contents);
                    Console.WriteLine("configuration file created - {0}", outputPath);
                }

                return(contents);
            }
        }
 public void IsolatedRazorEngineService_StaticSecurityCriticalModel_InSandbox()
 {
     using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
     {
         const string template = "<h1>Hello World @Model.Forename</h1>";
         const string expected = "<h1>Hello World TestForename</h1>";
         var          model    = new Person {
             Forename = "TestForename"
         };
         Assert.Throws <MethodAccessException>(() =>
         { // Because we cannot access the template constructor (as there is a SecurityCritical type argument)
             string result = service.RunCompile(template, "test", typeof(Person), model);
             Assert.AreEqual(expected, result);
         });
     }
 }
Esempio n. 19
0
        static void Main(string[] args)
        {
            using (var service = IsolatedRazorEngineService.Create())
            {
                const string template = "<h1>Animal Type: @Model.Type</h1>";
                const string expected = "<h1>Animal Type: Cat</h1>";

                dynamic model = new ExpandoObject();
                model.Type = "Cat";
                var result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
                if (!Equals(expected, result))
                {
                    throw new Exception(string.Format("{0} expected but got {1}", expected, result));
                }
            }
        }
        public void IsolatedRazorEngineService_StaticSecurityCriticalModelDynamicType_InSandBox()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                const string template = "<h1>Hello @Model.Forename</h1>";
                const string expected = "<h1>Hello Matt</h1>";

                var model = new Person {
                    Forename = "Matt"
                };
                Assert.Throws <SecurityException>(() =>
                { // this time we have no security critical type argument but we still should not be able to access it...
                    string result = service.RunCompile(template, "test", null, model);
                    Assert.AreEqual(expected, result);
                });
            }
        }
Esempio n. 21
0
        public void IsolatedRazorEngineService_CheckThatWeCanUseUnknownTypesAtExecuteTime()
        {
            using (var service = IsolatedRazorEngineService.Create(new ReferenceResolverConfigCreator(), () => SandboxCreator(new IPermission[] {
                new FileIOPermission(PermissionState.Unrestricted),
                new ReflectionPermission(PermissionState.Unrestricted)
            })))
            {
                var          template = @"
@{
    var t = new TestHelper.TestClass();
}
@t.TestProperty";
                const string expected = "\n\nTestPropert";

                string result = service.RunCompile(template, "test");

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void IsolatedRazorEngineService_BadTemplate_InSandbox()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                string file = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName());

                string template = @"
@using System.IO
@{
File.WriteAllText(""$file$"", ""BAD DATA"");
}".Replace("$file$", file.Replace("\\", "\\\\"));
                Assert.Throws <SecurityException>(() =>
                {
                    service.RunCompile(template, "test");
                });

                Assert.IsFalse(File.Exists(file));
            }
        }
        public void IsolatedRazorEngineService_VeryBadTemplate_InSandbox()
        {
            using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
            {
                string file = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName());

                string template = @"
@using System.IO
@using System.Security
@using System.Security.Permissions
@{
(new PermissionSet(PermissionState.Unrestricted)).Assert();
File.WriteAllText(""$file$"", ""BAD DATA"");
}".Replace("$file$", file.Replace("\\", "\\\\"));
                Assert.Throws <InvalidOperationException>(() =>
                { // cannot create a file in template
                    service.RunCompile(template, "test");
                });

                Assert.IsFalse(File.Exists(file));
            }
        }
Esempio n. 24
0
        /// <summary>Initializes a new instance of the <see cref="TemplateService" /> class.</summary>
        /// <param name="container">The container.</param>
        public TemplateService(IUnityContainer container)
        {
            this.eventAggregator = container.Resolve <IEventAggregator>();

            this.service = IsolatedRazorEngineService.Create(TemplateService.SandboxCreator);
        }
Esempio n. 25
0
        /// <summary>Initializes a new instance of the <see cref="TemplateService" /> class.</summary>
        /// <param name="container">The container.</param>
        public TemplateService(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;

            this.service = IsolatedRazorEngineService.Create(TemplateService.SandboxCreator);
        }
Esempio n. 26
0
 private EmailService(ITemplateServiceConfiguration configuration, bool isolated = false, Func <SmtpClient> createSmtpClient = null)
     : this(isolated ? IsolatedRazorEngineService.Create() : RazorEngineService.Create(configuration), createSmtpClient)
 {
 }