Example #1
0
        public void Tracing()
        {
            // Given
            string inputFolder = Path.Combine(Environment.CurrentDirectory, @".\Input");
            if (!Directory.Exists(inputFolder))
            {
                Directory.CreateDirectory(inputFolder);
            }
            ITrace trace = Substitute.For<ITrace>();
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.RootFolder.Returns(Environment.CurrentDirectory);
            context.InputFolder.Returns(inputFolder);
            context.Trace.Returns(trace);
            Engine engine = new Engine();
            engine.Configure();
            context.Assemblies.Returns(engine.Assemblies);
            IDocument document = Substitute.For<IDocument>();
            document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@{ ExecutionContext.Trace.Information(""Test""); }")));
            Razor razor = new Razor();

            // When
            razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            ITrace receivedTrace = context.Received().Trace; // Need to assign to dummy var to keep compiler happy
            trace.Received().Information("Test");
        }
Example #2
0
        public void SimpleTemplate()
        {
            // Given
            string inputFolder = Path.Combine(Environment.CurrentDirectory, @".\Input");
            if (!Directory.Exists(inputFolder))
            {
                Directory.CreateDirectory(inputFolder);
            }
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.RootFolder.Returns(Environment.CurrentDirectory);
            context.InputFolder.Returns(inputFolder);
            Engine engine = new Engine();
            engine.Configure();
            context.Assemblies.Returns(engine.Assemblies);
            IDocument document = Substitute.For<IDocument>();
            document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@for(int c = 0 ; c < 5 ; c++) { <p>@c</p> }")));
            Razor razor = new Razor();

            // When
            razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            document.Received(1).Clone(Arg.Any<string>());
            document.Received().Clone(" <p>0</p>  <p>1</p>  <p>2</p>  <p>3</p>  <p>4</p> ");
        }
 public ActionResult Edit(Razor.Datatables.Data.Person person, string Action)
 {
     switch (Action)
     {
         case "Cancel":
             return RedirectToAction("Datatable");                    
     }
     return View(person);
 }
Example #4
0
        private string Render(string emailTemplate, object model = null)
        {
            var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                            $"bin\\Templates\\{emailTemplate}.cshtml");

            var templateContent = File.ReadAllText(templatePath);

            var template = Razor.Parse(templateContent, model, emailTemplate);

            return(template);
        }
Example #5
0
        public string RR()
        {
            Stream stream = this.GetType().Assembly.GetManifestResourceStream("WebSocket.templte.cs");

            using (var streamR = new StreamReader(stream))
            {
                var templ = streamR.ReadToEnd();
                var x     = Razor.Parse(templ, new { Name = 33 });
                return(x);
            }
        }
Example #6
0
        public async Task Template_can_be_rendered_with_an_anonymous_model()
        {
            // Arrange
            var template = Razor.Compile("Hello, @Model.Foo!");

            // Act
            var result = await template.RenderAsync(new { Foo = "World" });

            // Assert
            result.Should().Be("Hello, World!");
        }
Example #7
0
 public string Render(TModel model)
 {
     try
     {
         return(Razor.Parse(this.templateContent, model, this.templateCacheKey));
     }
     catch (Exception exception)
     {
         throw new TemplateRenderException(string.Format("Error while rendering the template. Model Type: {0}", typeof(TModel)), exception);
     }
 }
Example #8
0
        public async Task Template_can_define_and_execute_local_code()
        {
            // Arrange
            var template = Razor.Compile("@{ int GetNumber() => 42; }@GetNumber()");

            // Act
            var result = await template.RenderAsync(null);

            // Assert
            result.Should().Be("42");
        }
Example #9
0
    public async Task Template_can_call_asynchronous_methods_on_a_model()
    {
        // Arrange
        var template = Razor.Compile("@await Model.GetSumAsync()");

        // Act
        var result = await template.RenderAsync(new TestModelWithAsyncMethod(2, 5));

        // Assert
        result.Should().Be("7");
    }
Example #10
0
 public GeneratorEngine(Project project)
 {
     this.project = project;
     Razor.SetTemplateBase(typeof(EasyGeneratorTemplateBase <>));
     Razor.DefaultTemplateService.Namespaces.Add("System.Collections.Generic");
     Razor.DefaultTemplateService.Namespaces.Add("System.Text");
     Razor.DefaultTemplateService.Namespaces.Add("EasyGenerator.Studio.Utils");
     Razor.DefaultTemplateService.Namespaces.Add("EasyGenerator.Studio.Model");
     Razor.DefaultTemplateService.Namespaces.Add("EasyGenerator.Studio.Controls");
     Razor.DefaultTemplateService.Namespaces.Add("EasyGenerator.Studio.DbHelper");
 }
Example #11
0
 static void MWMS_Init()
 {
     Sql.connectionString = @"server=" + ConfigurationManager.AppSettings["ServerIP"]
                            + ";uid=" + ConfigurationManager.AppSettings["Username"]
                            + ";pwd=" + ConfigurationManager.AppSettings["Password"]
                            + ";database=" + ConfigurationManager.AppSettings["DataBaseName"]
                            + ";min pool size=10;max pool size=100;connect timeout = 20;pooling=true;";
     Razor.SetTemplateService(MWMS.Template.BuildCode.TemplateService);
     RazorEngine.Razor.Compile("1", typeof(object[]), "_init_temp_code", true);
     // LoadMetadataReference();
 }
Example #12
0
        public void InlineHelperTemplateTest()
        {
            string template =
                @"@helper MyMethod(string name) {
    Hello @name
};
@MyMethod(Model.Name);! Welcome to Razor!";
            string result = Razor.Parse(template, new { Name = "World" });

            Assert.IsTrue(result.Contains("Hello World"));
        }
Example #13
0
        public MailMessage Parse(IMailTemplate template, object model)
        {
            var viewBag = new DynamicViewBag();

            viewBag.AddValue("Helper", new TemplateHelper());

            var content = template.ToStringContent();
            var result  = Razor.Parse(content, model, viewBag, template.Location);

            return(XmlMailSerializer.Deserialize(result));
        }
Example #14
0
        public string GetViewModelCode(Type type)
        {
            var template = GetTemplate("ViewModel");
            var model    = new ViewModel
            {
                ClassName     = GetClassName(type),
                PropertyNames = GetViewModelPropertyNames(type)
            };

            return(Razor.Parse(template, model));
        }
Example #15
0
        public RazorOperation(string outKey, string outType, string template, string templateModelType, IEnumerable <KeyValuePair <string, Template> > templates, IParameters parameters, ILogger logger)
            : base(outKey, outType, template, templates, parameters)
        {
            _templateModelType = templateModelType;

            var type = templateModelType == "dynamic" ? typeof(DynamicViewBag) : typeof(Dictionary <string, object>);

            Razor.Compile(Template, type, outKey, Logger);
            logger.Debug("Compiled {0} template with key {1}.", templateModelType, outKey);
            Name = string.Format("RazorOperation ({0})", outKey);
        }
Example #16
0
        public async Task Template_can_call_asynchronous_methods_with_cancellation_on_a_model()
        {
            // Arrange
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
            var template = Razor.Compile("@{ await Model.WaitIndefinitelyAsync(CancellationToken); }");

            // Act & assert
            await Assert.ThrowsAnyAsync <OperationCanceledException>(async() =>
                                                                     await template.RenderAsync(new TestModelWithAsyncMethodWithCancellation(), cts.Token)
                                                                     );
        }
Example #17
0
        public async Task Template_literals_are_always_rendered_without_encoding()
        {
            // Arrange
            var template = Razor.Compile("<div id=\"zzz\">@Model.Foo</div>");

            // Act
            var result = await template.RenderAsync(new { Foo = "bar" });

            // Assert
            result.Should().Be("<div id=\"zzz\">bar</div>");
        }
Example #18
0
        public async Task Evaluated_expressions_are_rendered_with_encoding_by_default()
        {
            // Arrange
            var template = Razor.Compile("@(\"<div id='foo'>bar</div>\")");

            // Act
            var result = await template.RenderAsync(null);

            // Assert
            result.Should().Be("&lt;div id=&#39;foo&#39;&gt;bar&lt;/div&gt;");
        }
Example #19
0
        public async Task Evaluated_expressions_can_be_rendered_without_encoding()
        {
            // Arrange
            var template = Razor.Compile("@Raw(\"<div id='foo'>bar</div>\")");

            // Act
            var result = await template.RenderAsync(null);

            // Assert
            result.Should().Be("<div id='foo'>bar</div>");
        }
        private void ProcessFile(GeneratorExecutionContext context, string filePath, string accessModifier, string content)
        {
            // Generate class name from file name
            var className = SanitizeIdentifier(Path.GetFileNameWithoutExtension(filePath));

            var code = Razor.ToCSharp(content, accessModifier, options =>
            {
                options.ConfigureClass((_, node) =>
                {
                    node.ClassName = className;
                });
            });

            // Get model type from the template's base class
            var modelTypeName = TryGetModelTypeName(code, className) ?? "dynamic";

            // Disable nullability checks on the entire file
            code = RemoveNullableDirectives(code)
                   .Insert(0, "#nullable disable" + Environment.NewLine);

            // Remove line mappings
            code = RemoveLineDirectives(code);

            // Add documentation to the class
            code = code.Insert(code.IndexOf($"{accessModifier} partial class", StringComparison.Ordinal), $@"
/// <summary>Template: {filePath}</summary>
/// <remarks>Generated by MiniRazor v{GeneratorVersion} on {DateTimeOffset.Now}.</remarks>
");

            // Extend the template with some additional code
            code = code.Insert(code.IndexOf("public async override", StringComparison.Ordinal), $@"
/// <summary>Renders the template using the specified writer.</summary>
public static async global::System.Threading.Tasks.Task RenderAsync(global::System.IO.TextWriter output, {modelTypeName} model)
{{
    var template = new {className}();
    template.Output = output;
    template.Model = model;

    await template.ExecuteAsync().ConfigureAwait(false);
}}

/// <summary>Renders the template to a string.</summary>
public static async global::System.Threading.Tasks.Task<string> RenderAsync({modelTypeName} model)
{{
    using (var output = new global::System.IO.StringWriter())
    {{
        await RenderAsync(output, model).ConfigureAwait(false);
        return output.ToString();
    }}
}}
");

            context.AddSource(className, code);
        }
Example #21
0
        public async Task Template_literals_in_attributes_are_always_rendered_without_encoding()
        {
            // Arrange
            var template = Razor.Compile("<div class=\"xyz @Model.Foo\">fff</div>");

            // Act
            var result = await template.RenderAsync(new { Foo = "bar" });

            // Assert
            result.Should().Be("<div class=\"xyz bar\">fff</div>");
        }
Example #22
0
 public string Parse(string template, object model)
 {
     try
     {
         return(Razor.RunCompile(template, template.Hash(), model?.GetType(), model));
     }
     catch (TemplateParsingException error)
     {
         throw new BusinessException("模版配置错误,template:" + template, error);
     }
 }
Example #23
0
    public async Task Template_can_reference_a_model()
    {
        // Arrange
        var template = Razor.Compile("@Model.Foo & @Model.Number");

        // Act
        var result = await template.RenderAsync(new TestModel("bar", 42));

        // Assert
        result.Should().Be("bar & 42");
    }
Example #24
0
        public static void BuildContent(List list, IList <IListField> fields, ListItem item, string contentTemplate, StringBuilder stringBuilder, UrlHelper urlHelper)
        {
            if (string.IsNullOrEmpty(contentTemplate))
            {
                return;
            }

            var templateName = string.Format("LIST_CONTENT_ITEM_TEMPLATE_{0}", contentTemplate.GetHashCode());

            var itemUrl = urlHelper.Content(string.Format("~/{0}/{1}", list.Url, item.Slug));

            var values = item.Values.SharpDeserialize <IDictionary <string, object> >() ?? new Dictionary <string, object>();

            var model = new TemplateViewModel();

            foreach (var pair in values)
            {
                var field = fields.FirstOrDefault(x => x.Name == pair.Key);
                if (field == null)
                {
                    continue;
                }
                var localValue = pair;
                model[pair.Key] = args => field.RenderField(localValue.Value, args);
            }

            model["Title"]           = args => item.Title;
            model["MetaKeywords"]    = args => item.MetaKeywords;
            model["MetaDescription"] = args => item.MetaDescription;
            model["ListItemUrl"]     = args => itemUrl;
            model["PictureUrl"]      = args => item.PictureUrl;

            model["CreatedDate"] = args =>
            {
                if (args != null && args.Length > 0)
                {
                    return(item.CreatedDate.ToString(Convert.ToString(args[0])));
                }
                return(item.CreatedDate);
            };

            model["ModifiedDate"] = args =>
            {
                if (args != null && args.Length > 0)
                {
                    return(item.ModifiedDate.ToString(Convert.ToString(args[0])));
                }
                return(item.ModifiedDate);
            };

            var template = Razor.GetTemplate(contentTemplate, model, templateName);

            stringBuilder.Append(template.Run(new ExecuteContext()));
        }
Example #25
0
        public FluentMailer(IFluentMailerMessageBodyCreatorFactory fluentMailerMessageBodyCreatorFactory)
        {
            _fluentMailerMessageBodyCreatorFactory = fluentMailerMessageBodyCreatorFactory;

            var templateConfig = new TemplateServiceConfiguration
            {
                BaseTemplateType = typeof(MailerModuleTemplateBase <>),
                Resolver         = new MailerModuleTemplateResolver()
            };

            Razor.SetTemplateService(new TemplateService(templateConfig));
        }
        public string Render(ChangeManifest manifest)
        {
            if (!File.Exists(_templateFile))
            {
                throw new ArgumentException("Template file could not be found: {0}", _templateFile);
            }

            var defaultTemplate = File.ReadAllText(_templateFile);
            var result          = Razor.Parse(defaultTemplate, manifest);

            return(result);
        }
        public override void Start(object sender, StartEventArgs args)
        {
            _Writer = File.CreateText(Path);
            if (HeadTemplate == null)
            {
                return;
            }

            string content = Razor.Parse(HeadTemplate, GlobalModel.ToDynamicObject());

            _Writer.WriteLine(content);
        }
Example #28
0
 private string GetHtml <T>(T model, string viewPath)
 {
     try
     {
         var physicalPath = Server.MapPath(viewPath);
         var html         = System.IO.File.ReadAllText(physicalPath);
         return(Razor.Parse(html, model));
     }
     catch (Exception ex) {
         return("<html><body><div style='width:100%;text-align:center'><h1>Report Load Failed.Something Went Wrong!</h1></div></body></html>");
     }
 }
Example #29
0
        /// <summary>
        /// The main method of the plugin.
        /// Gets run in its own thread by the controller and should stop gracefully on a <see cref="System.Threading.ThreadAbortException"/>.
        /// </summary>
        public override void Run()
        {
            var timer = new Stopwatch();

            while (true)
            {
                while (!clientManialinksNeedRefresh)
                {
                    Thread.Sleep(100);
                }

                clientManialinksNeedRefresh = false;
                timer.Restart();

                foreach (var client in controller.ClientsManager.CurrentClients.Select(client => client.Login))
                {
                    var clientManialinkElements = new List <string>();

                    List <string> clientDisabledPluginDisplays;
                    clientsDisabledPluginDisplays.TryGetValue(client, out clientDisabledPluginDisplays);
                    clientDisabledPluginDisplays = clientDisabledPluginDisplays ?? new List <string>();

                    // Iterate over all the plugins that aren't on the disabled-list of the client.
                    foreach (var manialinkPages in providers.Where(provider => !clientDisabledPluginDisplays.Contains(GetName(provider.GetType())))
                             .Select(provider => provider.ManialinkPages.ToDictionary(entry => entry.Key, entry => entry.Value)))
                    {
                        // See if there's a value specifically for the client, or otherwise one for all.
                        if (manialinkPages.ContainsKey(client))
                        {
                            clientManialinkElements.Add(manialinkPages[client]);
                        }
                        else if (manialinkPages.ContainsKey("*"))
                        {
                            clientManialinkElements.Add(manialinkPages["*"]);
                        }
                    }

                    var clientManialink = WebUtility.HtmlDecode(Razor.Parse(manialinkTemplate, clientManialinkElements, client));

                    controller.CallMethod(new SendDisplayManialinkPageToLogin(client, clientManialink, 0, false), 0);
                }

                timer.Stop();

                var delay = Config.ManialinkRefreshInterval - timer.ElapsedMilliseconds;

                if (delay > 0)
                {
                    Thread.Sleep((int)delay);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }
Example #30
0
        static void Main(string[] args)
        {
            Comprobante   oComprobante;
            string        pathXML     = @"E:\ASP NET\XMLtoPDF\XMLtoPDF\xml\archivoXML3.xml";
            XmlSerializer oSerializer = new XmlSerializer(typeof(Comprobante));

            using (StreamReader reader = new StreamReader(pathXML))
            {
                oComprobante = (Comprobante)oSerializer.Deserialize(reader);
                //var tmp = oComprobante.Impuestos.TotalImpuestosTrasladados
                foreach (var oComplemento in oComprobante.Complemento)
                {
                    foreach (var oComplementoInterior in oComplemento.Any)
                    {
                        if (oComplementoInterior.Name.Contains("TimbreFiscalDigital"))
                        {
                            XmlSerializer oSerializerComplemento = new XmlSerializer(typeof(TimbreFiscalDigital));
                            using (var readerComplemento = new StringReader(oComplementoInterior.OuterXml))
                            {
                                oComprobante.TimbreFiscalDigital = (TimbreFiscalDigital)oSerializerComplemento.Deserialize(readerComplemento);
                            }
                        }
                    }
                }
            }

            //Paso 2 Aplicando Razor y haciendo HTML a PDF

            string path            = AppDomain.CurrentDomain.BaseDirectory + "/";
            string pathHTMLTemp    = path + "miHTML.html";//temporal
            string pathHTPlantilla = path + "plantilla.html";
            string sHtml           = GetStringOfFile(pathHTPlantilla);
            string resultHtml      = "";

            resultHtml = Razor.Parse(sHtml, oComprobante);

            Console.WriteLine(resultHtml);
            //Creamos el archivo temporal
            File.WriteAllText(pathHTMLTemp, resultHtml);
            string           pathWKHTMLTOPDF   = @"E:\ASP NET\XMLtoPDF\XMLtoPDF\wkhtmltopdf\wkhtmltopdf.exe";
            ProcessStartInfo oProcessStartInfo = new ProcessStartInfo();

            oProcessStartInfo.UseShellExecute = false;
            oProcessStartInfo.FileName        = pathWKHTMLTOPDF;
            oProcessStartInfo.Arguments       = "miHTML.html miPDF.pdf";
            using (Process oProcess = Process.Start(oProcessStartInfo))
            {
                oProcess.WaitForExit();
            }
            //eliminamos el archivo temporal
            File.Delete(pathHTMLTemp);
            Console.Read();
        }
Example #31
0
        public NotifyHook(IRootPathProvider rootPathProvider)
        {
            Post["/notify"] = x =>
            {
                var  rootPath = rootPathProvider.GetRootPath();
                bool skipEmail;
                bool.TryParse(Request.Query["skipEmail"], out skipEmail);

                PushData pushData = JsonConvert.DeserializeObject <PushData>(Request.Form["payload"]);

                var oldestCommit             = pushData.Commits.OrderBy(c => c.Timestamp).First();
                var oldestCommitMsgFirstLine = oldestCommit.Message.Split('\n')[0];

                var subject = string.Format("[{0}/{1}, {2}] ({3}) {4}",
                                            pushData.Repository.Owner.Name,
                                            pushData.Repository.Name,
                                            pushData.Branch,
                                            oldestCommit.Author.Username,
                                            oldestCommitMsgFirstLine);

                var template = File.ReadAllText(Path.Combine(rootPath, @"Views", @"Notify.cshtml"));
                var body     = Razor.Parse(template, pushData);

                if (skipEmail)
                {
                    return(body);
                }

                var from     = ConfigurationManager.AppSettings["EmailsFrom"];
                var fromName = ConfigurationManager.AppSettings["EmailsFromName"];

                var mailMessage = new MailMessage
                {
                    From       = new MailAddress(from, (string.IsNullOrEmpty(fromName) ? from : fromName)),
                    Subject    = subject,
                    Body       = body,
                    IsBodyHtml = true
                };

                var replyTo     = ConfigurationManager.AppSettings["EmailsReplyTo"];
                var replyToName = ConfigurationManager.AppSettings["EmailsReplyToName"];
                if (!string.IsNullOrEmpty(replyTo))
                {
                    mailMessage.ReplyToList.Add(new MailAddress(replyTo, (string.IsNullOrEmpty(replyToName) ? replyTo : replyToName)));
                }

                mailMessage.Headers.Add("gh-repo", pushData.Repository.Name);
                mailMessage.To.Add(ConfigurationManager.AppSettings["EmailsTo"]);
                new SmtpClient().Send(mailMessage);

                return("email sent");
            };
        }
Example #32
0
        public void Can_compile_template_with_RenderBody()
        {
            const string html = "@{ Layout = \"TheLayout.cshtml\"; }This is my sample template, @section Title {<h1>Hello @Model.Name!</h1>}";

            Razor.Compile(html, "simple4");

            var template = Razor.DefaultTemplateService.ExecuteTemplate(new { Name = "World" }, "simple4");

            Console.WriteLine(template.Result);

            Assert.That(template.Result, Is.EqualTo("<html><body><div><h1>Hello World!</h1></div>This is my sample template, </body></html>"));
        }
Example #33
0
        public string Build(string repositoryName, string branchName, string tagName, string[] taskPrefixes, string templateName)
        {
            var notes        = notesBuilder.Build(repositoryName, branchName, tagName, taskPrefixes);
            var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates",
                                            string.Format("{0}.cshtml", templateName));
            var templateBody = File.ReadAllText(templatePath);

            return(Razor.Parse(templateBody, new ReportModel
            {
                Notes = notes
            }));
        }
Example #34
0
        public void LoadLayoutFile()
        {
            // Given
            Engine engine = new Engine();
            engine.InputFolder = @"TestFiles\Input\";
            ReadFiles readFiles = new ReadFiles(@"Layout\Test.cshtml");
            Razor razor = new Razor();
            engine.Pipelines.Add("Pipeline", readFiles, razor);

            // When
            engine.Execute();

            // Then
            Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
            Assert.AreEqual("LAYOUT\r\n\r\n<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().Content);
        }
Example #35
0
        public void AlternateIgnorePrefix()
        {
            // Given
            Engine engine = new Engine();
            engine.InputFolder = @"TestFiles\Input\";
            ReadFiles readFiles = new ReadFiles(@"AlternateIgnorePrefix\*.cshtml");
            Razor razor = new Razor().IgnorePrefix("Ignore");
            engine.Pipelines.Add("Pipeline", readFiles, razor);

            // When
            engine.Execute();

            // Then
            Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
            Assert.AreEqual(@"<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().Content);
        }
Example #36
0
            public void SimpleTemplate()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = Substitute.For<IDocument>();
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@for(int c = 0 ; c < 5 ; c++) { <p>@c</p> }")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, " <p>0</p>  <p>1</p>  <p>2</p>  <p>3</p>  <p>4</p> ");
            }
Example #37
0
        public void AlternateViewStartPath()
        {
            // Given
            Engine engine = new Engine();
            engine.InputFolder = @"TestFiles\Input\";
            ReadFiles readFiles = new ReadFiles(@"AlternateViewStartPath\Test.cshtml");
            Razor razor = new Razor().WithViewStart(@"AlternateViewStart\_ViewStart.cshtml");
            Meta meta = new Meta("Content", (x, y) => x.Content);
            engine.Pipelines.Add("Pipeline", readFiles, razor, meta);

            // When
            engine.Execute();

            // Then
            Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
            Assert.AreEqual("LAYOUT\r\n<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content"));
        }
Example #38
0
        public void IgnoresUnderscoresByDefault()
        {
            // Given
            Engine engine = new Engine();
            engine.InputFolder = @"TestFiles\Input\";
            ReadFiles readFiles = new ReadFiles(@"IgnoreUnderscores\*.cshtml");
            Razor razor = new Razor();
            Meta meta = new Meta("Content", (x, y) => x.Content);
            engine.Pipelines.Add("Pipeline", readFiles, razor, meta);

            // When
            engine.Execute();

            // Then
            Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
            Assert.AreEqual("LAYOUT\r\n\r\n<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content"));
        }
Example #39
0
            public void AlternateIgnorePrefix()
            {
                // Given
                Engine engine = new Engine();
                engine.RootFolder = TestContext.CurrentContext.TestDirectory;
                engine.InputFolder = @"TestFiles\Input\";
                ReadFiles readFiles = new ReadFiles(@"AlternateIgnorePrefix\*.cshtml");
                Razor razor = new Razor().IgnorePrefix("Ignore");
                Meta meta = new Meta("Content", (x, y) => x.Content);
                engine.Pipelines.Add("Pipeline", readFiles, razor, meta);

                // When
                engine.Execute();

                // Then
                Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
                Assert.AreEqual(@"<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content"));
            }
Example #40
0
            public void Tracing()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = Substitute.For<IDocument>();
                TraceListener traceListener = new TraceListener();
                Trace.AddListener(traceListener);
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@{ Trace.Information(""Test""); }")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                Trace.RemoveListener(traceListener);
                CollectionAssert.Contains(traceListener.Messages, "Test");
            }
Example #41
0
        public void LoadSimpleTemplateFile()
        {
            // Given
            Engine engine = new Engine();
            engine.InputFolder = @"TestFiles\Input\";
            ReadFiles readFiles = new ReadFiles(@"SimpleTemplate\Test.cshtml");
            Razor razor = new Razor();
            Meta meta = new Meta("Content", (x, y) => x.Content);
            engine.Pipelines.Add("Pipeline", readFiles, razor, meta);

            // When
            engine.Execute();

            // Then
            Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
            Assert.AreEqual(@"<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content"));
        }
 public override void BuildSpan(SpanBuilder span, Razor.Text.SourceLocation start, string content)
 {
     throw new NotImplementedException();
 }
Example #43
0
            public void DocumentAsModel()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = GetDocument("C:/Temp/temp.txt", @"<p>@Model.Source</p>");
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, @"<p>file:///C:/Temp/temp.txt</p>");  // The slash prefix is just added by our dumb mock
            }
		public bool ApplyChanges(ISupportsEditing editableObject, Razor.Configuration.SupportedEditingActions actions)
		{
			XmlConfigurationCategoryCollection categories = editableObject as XmlConfigurationCategoryCollection;
			if (categories != null)
			{					
				foreach(XmlConfigurationCategory category in categories)
				{					
					XmlConfigurationCategory myCategory = this[category.ElementName];
					if (myCategory != null)
					{
						try
						{
							myCategory.ApplyChanges((ISupportsEditing)category, actions);
						}
						catch(System.Exception systemException)
						{
							System.Diagnostics.Trace.WriteLine(systemException);
						}
					}
				}

			}
			return true;
		}
		public bool ApplyChanges(ISupportsEditing editableObject, Razor.Configuration.SupportedEditingActions actions)
		{
			XmlConfigurationOptionCollection options = editableObject as XmlConfigurationOptionCollection;
			if (options != null)
			{	
				foreach(XmlConfigurationOption option in options)
				{					
					XmlConfigurationOption myOption = this[option.ElementName];
					if (myOption != null)
					{
						try
						{
							myOption.ApplyChanges((ISupportsEditing)option, actions);
						}
						catch(System.Exception systemException)
						{
							System.Diagnostics.Trace.WriteLine(systemException);
						}
					}
				}

			}
			return true;
		}
Example #46
0
        public void Metadata()
        {
            // Given
            string inputFolder = Path.Combine(Environment.CurrentDirectory, @".\Input");
            if (!Directory.Exists(inputFolder))
            {
                Directory.CreateDirectory(inputFolder);
            }
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.RootFolder.Returns(Environment.CurrentDirectory);
            context.InputFolder.Returns(inputFolder);
            Engine engine = new Engine();
            engine.Configure();
            context.Assemblies.Returns(engine.Assemblies);
            IDocument document = Substitute.For<IDocument>();
            document.Metadata.Get("SourceFileBase", "/").Returns("/");
            document.Metadata["MyKey"].Returns("MyValue");
            List<string> items = new List<string>();
            document
                .When(x => x.Clone(Arg.Any<string>()))
                .Do(x => items.Add(x.Arg<string>()));
            document.Content.Returns(@"<p>@Metadata[""MyKey""]</p>");
            Razor razor = new Razor();

            // When
            razor.Execute(new[] { document }, context).ToList();

            // Then
            document.Received().Clone(Arg.Any<string>());
            Assert.AreEqual(1, items.Count());
            Assert.AreEqual("<p>MyValue</p>", items.First());
        }
Example #47
0
        public void SimpleTemplate()
        {
            // Given
            string inputFolder = Path.Combine(Environment.CurrentDirectory, @".\Input");
            if (!Directory.Exists(inputFolder))
            {
                Directory.CreateDirectory(inputFolder);
            }
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.RootFolder.Returns(Environment.CurrentDirectory);
            context.InputFolder.Returns(inputFolder);
            Engine engine = new Engine();
            engine.Configure();
            context.Assemblies.Returns(engine.Assemblies);
            IDocument document = Substitute.For<IDocument>();
            document.Metadata.Get("SourceFileBase", "/").Returns("/");
            List<string> items = new List<string>();
            document
                .When(x => x.Clone(Arg.Any<string>()))
                .Do(x => items.Add(x.Arg<string>()));
            document.Content.Returns(@"@for(int c = 0 ; c < 5 ; c++) { <p>@c</p> }");
            Razor razor = new Razor();

            // When
            razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

            // Then
            document.Received().Clone(Arg.Any<string>());
            Assert.AreEqual(1, items.Count());
            Assert.AreEqual(" <p>0</p>  <p>1</p>  <p>2</p>  <p>3</p>  <p>4</p> ", items.First());
        }
Example #48
0
            public void LoadViewStartAndLayoutFile()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = GetDocument(@"ViewStartAndLayout/Test.cshtml",
@"<p>This is a test</p>");
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document,
@"LAYOUT2
<p>This is a test</p>");
            }
Example #49
0
            public void AlternateViewStartPath()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = GetDocument(@"AlternateViewStartPath/Test.cshtml",
@"<p>This is a test</p>");
                Razor razor = new Razor().WithViewStart(@"AlternateViewStart/_ViewStart.cshtml");

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document,
@"LAYOUT3
<p>This is a test</p>");
            }
Example #50
0
            public void IgnoresUnderscoresByDefault()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document1 = GetDocument(@"IgnoreUnderscores/Test.cshtml",
@"@{
	Layout = ""_Layout.cshtml"";
}
<p>This is a test</p>");
                IDocument document2 = GetDocument(@"IgnoreUnderscores/_Layout.cshtml",
@"LAYOUT4
@RenderBody()");
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document1, document2 }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document1,
@"LAYOUT4

<p>This is a test</p>");
            }
Example #51
0
            public void Document()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = Substitute.For<IDocument>();
                document.Source.Returns(new FilePath("C:/Temp/temp.txt"));
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"<p>@Document.Source</p>")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, @"<p>file:///C:/Temp/temp.txt</p>");
            }
Example #52
0
            public void RenderLayoutSectionOnMultipleExecution()
            {
                // Given
                Engine engine = new Engine();
                engine.RootFolder = TestContext.CurrentContext.TestDirectory;
                engine.InputFolder = @"TestFiles\Input\";
                ReadFiles readFiles = new ReadFiles(@"LayoutWithSection\Test.cshtml");
                Razor razor = new Razor();
                Meta meta = new Meta("Content", (x, y) => x.Content);
                engine.Pipelines.Add("Pipeline", readFiles, razor, meta);

                // When
                engine.Execute();
                engine.Execute();

                // Then
                Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count());
                Assert.AreEqual("LAYOUT\r\n\r\n<p>Section Content</p>\r\n\r\n\r\n<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content"));
            }
Example #53
0
            public void AlternateIgnorePrefix()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document1 = GetDocument(@"AlternateIgnorePrefix/Test.cshtml",
@"<p>This is a test</p>");
                IDocument document2 = GetDocument(@"AlternateIgnorePrefix/IgnoreMe.cshtml",
@"<p>Ignore me</p>");
                Razor razor = new Razor().IgnorePrefix("Ignore");

                // When
                razor.Execute(new[] { document1, document2 }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document1,
@"<p>This is a test</p>");
            }
Example #54
0
            public void Metadata()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = Substitute.For<IDocument>();
                document["MyKey"].Returns("MyValue");
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"<p>@Metadata[""MyKey""]</p>")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, "<p>MyValue</p>");
            }
Example #55
0
            public void RenderLayoutSectionOnMultipleExecution()
            {
                // Given
                Engine engine = new Engine();
                IExecutionContext context = GetExecutionContext(engine);
                IDocument document = GetDocument(@"LayoutWithSection/Test.cshtml",
@"@{
	Layout = ""_Layout.cshtml"";
}
@section MySection {
<p>Section Content</p>
}
<p>This is a test</p>");
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(2).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document,
@"LAYOUT5

<p>Section Content</p>


<p>This is a test</p>");
            }
Example #56
0
            public void Tracing()
            {
                // Given
                string inputFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, @".\Input");
                if (!Directory.Exists(inputFolder))
                {
                    Directory.CreateDirectory(inputFolder);
                }
                IExecutionContext context = Substitute.For<IExecutionContext>();
                context.RootFolder.Returns(TestContext.CurrentContext.TestDirectory);
                context.InputFolder.Returns(inputFolder);
                Engine engine = new Engine();
                engine.Configure();
                context.Assemblies.Returns(engine.Assemblies);
                context.Namespaces.Returns(engine.Namespaces);
                IDocument document = Substitute.For<IDocument>();
                TraceListener traceListener = new TraceListener();
                Trace.AddListener(traceListener);
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@{ Trace.Information(""Test""); }")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();  // Make sure to materialize the result list

                // Then
                Trace.RemoveListener(traceListener);
                CollectionAssert.Contains(traceListener.Messages, "Test");
            }
Example #57
0
        public void Metadata()
        {
            // Given
            string inputFolder = Path.Combine(Environment.CurrentDirectory, @".\Input");
            if (!Directory.Exists(inputFolder))
            {
                Directory.CreateDirectory(inputFolder);
            }
            IExecutionContext context = Substitute.For<IExecutionContext>();
            context.RootFolder.Returns(Environment.CurrentDirectory);
            context.InputFolder.Returns(inputFolder);
            Engine engine = new Engine();
            engine.Configure();
            context.Assemblies.Returns(engine.Assemblies);
            IDocument document = Substitute.For<IDocument>();
            document.Metadata["MyKey"].Returns("MyValue");
            document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"<p>@Metadata[""MyKey""]</p>")));
            Razor razor = new Razor();

            // When
            razor.Execute(new[] { document }, context).ToList();

            // Then
            document.Received(1).Clone(Arg.Any<string>());
            document.Received().Clone("<p>MyValue</p>");
        }
Example #58
0
            public void Document()
            {
                // Given
                string inputFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, @".\Input");
                if (!Directory.Exists(inputFolder))
                {
                    Directory.CreateDirectory(inputFolder);
                }
                IExecutionContext context = Substitute.For<IExecutionContext>();
                context.RootFolder.Returns(TestContext.CurrentContext.TestDirectory);
                context.InputFolder.Returns(inputFolder);
                Engine engine = new Engine();
                engine.Configure();
                context.Assemblies.Returns(engine.Assemblies);
                IDocument document = Substitute.For<IDocument>();
                document.Source.Returns(@"C:\Temp\temp.txt");
                document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"<p>@Document.Source</p>")));
                Razor razor = new Razor();

                // When
                razor.Execute(new[] { document }, context).ToList();

                // Then
                context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>());
                context.Received().GetDocument(document, @"<p>C:\Temp\temp.txt</p>");
            }
		public virtual bool ApplyChanges(ISupportsEditing editableObject, Razor.Configuration.SupportedEditingActions actions)
		{
			if (actions == SupportedEditingActions.None)
				return true;

			XmlConfigurationElement element = editableObject as XmlConfigurationElement;			
			if (element != null)
			{
				/// do we match in full paths?
				if (string.Compare(this.Fullpath, element.Fullpath, true) == 0)
				{
					/// does the element have changes, if not we don't need to bother
					if (element.HasChanges)
					{				
						/// yes so apply it's changed features
						this.ElementName = element.ElementName;
						this.Description = element.Description;
						this.Category = element.Category;
						this.DisplayName = element.DisplayName;
						this.Hidden = element.Hidden;
						this.Readonly = element.Readonly;
						this.Persistent = element.Persistent;
					}
					return true;
				}
			}


			return false;
		}