Beispiel #1
0
 /// <summary>
 /// </summary>
 /// <returns></returns>
 internal static string ConnectionList()
 {
     var fileName = FilePath + "\\ConnectionList.htm";
     String content;
     var stream = new StreamReader(fileName);
     content = stream.ReadToEnd();
     var connectionList = String.Empty;
     foreach (var item in
         RuntimeMongoDBContext._mongoConnectionConfigList.Values)
     {
         if (item.ReplSetName == String.Empty)
         {
             connectionList += "<li><a href = 'Connection?" + item.ConnectionName + "'>" + item.ConnectionName +
                               "@" + (item.Host == String.Empty ? "localhost" : item.Host)
                               + (item.Port == 0 ? String.Empty : ":" + item.Port) + "</a></li>" +
                               Environment.NewLine;
         }
         else
         {
             connectionList += "<li><a href = 'Connection?" + item.ConnectionName + "'>" + item.ConnectionName +
                               "</a></li>" + Environment.NewLine;
         }
     }
     var config = new TemplateServiceConfiguration();
     //config.ReferenceResolver = (IReferenceResolver)((new UseCurrentAssembliesReferenceResolver()).GetReferences(null));
     config.Debug = true;
     var ser = new TemplateService(config);
     ser.AddNamespace("MongoUtility.Core");
     ser.AddNamespace("SystemUtility");
     Razor.SetTemplateService(ser);
     content = Razor.Parse(content, new {SystemConfig.config.ConnectionList});
     return content;
 }
Beispiel #2
0
        static void Main(string[] agrs)
        {
            string template = "This is my sample template, Hello @Model.Name!";
            string result = Razor.Parse(template, new { Name = "World" });
            Console.WriteLine(result);

            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType = typeof(CustomBaseTemplate<>),
                Resolver = new CustomTemplateResolver(),
            };

            var service = new TemplateService(config);

            Razor.SetTemplateService(service);

            string template3 = "My name @Html.Raw(Model.HtmlString) @Model.HtmlString in UPPER CASE is @Model.Name";
            string result3 = Razor.Parse(template3, new { Name = "Max", Email ="*****@*****.**", HtmlString = "<a href=\"/web/x.html\"> asd </a>" });

            Console.WriteLine(result3);

            var context = new ExecuteContext();
            var parsedView = Razor.Resolve("TestView").Run(context);
            Console.WriteLine(parsedView);

            Console.ReadKey();
        }
Beispiel #3
0
        static void StronglyTypedModel()
        {
            var welcomeEmailTemplatePath = Path.Combine(TemplateFolderPath, "WelcomeEmailStronglyTyped.cshtml");

            // Generate the email body from our email template
            var stronglyTypedModel = new UserModel() { Name = "Sarah", Email = "*****@*****.**", IsPremiumUser = false };

            var templateService = new TemplateService();
            var emailHtmlBody = templateService.Parse(File.ReadAllText(welcomeEmailTemplatePath), stronglyTypedModel, null, null);

            // Send the email
            var email = new MailMessage()
            {
                Body = emailHtmlBody,
                IsBodyHtml = true,
                Subject = "Welcome (generated from strongly-typed model)"
            };

            email.To.Add(new MailAddress(stronglyTypedModel.Email, stronglyTypedModel.Name));
            // The From field will be populated from the app.config value by default

            var smtpClient = new SmtpClient();
            smtpClient.Send(email);

            // In the real world, you'll probably want to use async version instead:
            // await smtpClient.SendMailAsync(email);
        }
        //[Test]
        public void IntegrationTest()
        {
            const string templatePath = @"..\..\Test Templates\Modeled Basic Template.odt";
            const string reportPath = @"..\..\Generated Reports\Very Basic Report.odt";
            const string expectedReportPath = @"..\..\Expected Report Outputs\Very Basic Report.odt";
            var templateFactory = new TemplateFactory();
            var zipFactory = new ZipFactory();
            var readerFactory = new StreamReaderWrapperFactory();
            var zipHandlerService = new ZipHandlerService( readerFactory );
            var buildOdfMetadataService = new BuildOdfMetadataService();
            var xmlNamespaceService = new XmlNamespaceService();
            var xDocumentParserService = new XDocumentParserService();
            var odfHandlerService = new OdfHandlerService( zipFactory, zipHandlerService, buildOdfMetadataService,
                                                           xmlNamespaceService, xDocumentParserService );

            var templateService = new TemplateBuilderService( templateFactory, odfHandlerService,
                                                              xmlNamespaceService, xDocumentParserService );
            var document = File.ReadAllBytes( templatePath );

            var template = templateService.BuildTemplate( document );
            var razorTemplateService = new TemplateService();
            var compileService = new CompileService( razorTemplateService );
            compileService.Compile( template, "Template 1" );

            var reportService = new ReportGeneratorService( new ZipFactory(), razorTemplateService );
            using( var report = new FileStream( reportPath, FileMode.Create ) )
            {
                reportService.BuildReport( template, new BasicModel {Name = "Fancypants McSnooterson"}, report );
            }
            var diffs = GetDifferences( expectedReportPath, reportPath );
            var thereAreDifferences = diffs.HasDifferences();
            Assert.That( !thereAreDifferences );
        }
        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);
            }
        }
Beispiel #6
0
 public String Render(TemplateModel templateModel)
 {
     var assembly = Assembly.GetExecutingAssembly();
     string template;
     using (var sr = new StreamReader(assembly.GetManifestResourceStream("HotGlue.Generator.MVCRoutes.Templates.Routing.razor")))
     {
         template = sr.ReadToEnd();
     }
     var config = new TemplateServiceConfiguration
         {
             BaseTemplateType = typeof (JavaScriptRoutingTemplateBase<>)
         };
     string result;
     try
     {
         using (var service = new TemplateService(config))
         {
             Razor.SetTemplateService(service);
             result = Razor.Parse(template, templateModel);
             return result;
         }
     }
     catch (TemplateCompilationException ex)
     {
         foreach (var error in ex.Errors)
         {
             Console.WriteLine(error.ErrorText);
         }
         throw;
     }
 }
Beispiel #7
0
        static void DynamicModel()
        {
            var welcomeEmailTemplatePath = Path.Combine(TemplateFolderPath, "WelcomeEmailDynamic.cshtml");

            // Generate the email body from our email template
            // Note: the RazorEngine library supports using an anonymous type as a model without having to transform it to an Expando object first.
            var anonymousModel = new { Name = "Sarah", Email = "*****@*****.**", IsPremiumUser = false };

            var templateService = new TemplateService();
            var emailHtmlBody = templateService.Parse(File.ReadAllText(welcomeEmailTemplatePath), anonymousModel, null, null);

            // Send the email
            var email = new MailMessage()
            {
                Body = emailHtmlBody,
                IsBodyHtml = true,
                Subject = "Welcome (generated from dynamic model)"
            };

            email.To.Add(new MailAddress(anonymousModel.Email, anonymousModel.Name));
            // The From field will be populated from the app.config value by default

            var smtpClient = new SmtpClient();
            smtpClient.Send(email);
        }
        /// <summary>
        /// Creates an instance of a <see cref="TemplateService"/>.
        /// </summary>
        /// <param name="configuration">The <see cref="TemplateServiceConfigurationElement"/> that represents the configuration.</param>
        /// <param name="defaultNamespaces">The enumerable of namespaces to add as default.</param>
        /// <returns>A new instance of <see cref="TemplateService"/>.</returns>
        public static TemplateService CreateTemplateService(TemplateServiceConfigurationElement configuration, IEnumerable<string> defaultNamespaces = null)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            ILanguageProvider provider = null;
            MarkupParser parser = null;
            Type templateBaseType = null;

            if (!string.IsNullOrEmpty(configuration.LanguageProvider))
                provider = (ILanguageProvider)GetInstance(configuration.LanguageProvider);

            if (!string.IsNullOrEmpty(configuration.MarkupParser))
                parser = (MarkupParser)GetInstance(configuration.MarkupParser);

            if (!string.IsNullOrEmpty(configuration.TemplateBase))
                templateBaseType = GetType(configuration.TemplateBase);

            var namespaces = configuration.Namespaces
                .Cast<NamespaceConfigurationElement>()
                .Select(n => n.Namespace);

            if (defaultNamespaces != null)
            {
                namespaces = defaultNamespaces
                    .Concat(namespaces)
                    .Distinct();
            }

            var service = new TemplateService(provider, templateBaseType, parser);
            foreach (string ns in namespaces)
                service.Namespaces.Add(ns);

            return service;
        }
Beispiel #9
0
        public static void Main(string[] args)
        {
            if (args.Length >= 2)
            {
                var fileEncoding = Encoding.UTF8;
                var config = new FluentTemplateServiceConfiguration(c => c.WithEncoding(RazorEngine.Encoding.Raw));
                using (var myConfiguredTemplateService = new TemplateService(config))
                {
                    RazorEngine.Razor.SetTemplateService(myConfiguredTemplateService);
                    if (args.Length > 3 && args[2] == "-r")
                    {
                        Assembly.LoadFrom(args[3]);
                    }

                    string razorContent = File.ReadAllText(args[0], fileEncoding);
                    string outputContent = RazorEngine.Razor.Parse(razorContent);
                    File.WriteAllText(args[1], outputContent, fileEncoding);
                }
            }
            else
            {
                Console.WriteLine("Usage: RazorParser fileName.cshtml output.[js|ts|css|less] -r Referenced.dll");
            }
            Console.WriteLine("Done");
        }
Beispiel #10
0
 private static string GetEmailBody(string template, object data)
 {
     string path = HttpContext.Current.Server
                .MapPath("~/") + template;
     TemplateService templateService = new TemplateService();
     var emailHtmlBody = templateService.Parse(File.ReadAllText(path), data, null, null);
     return PreMailer.Net.PreMailer.MoveCssInline(emailHtmlBody, true).Html;
 }
        private void ProcessSubContent(TemplateService service, Match match, dynamic model)
        {
            var subName = match.Groups[1].Value; // got an include/layout match?
            var subContent = GetContent(subName); // go get that template then
            ProcessContent(subContent, service, model); // recursively process it

            service.GetTemplate(subContent, model, subName); // then add it to the service
        }
Beispiel #12
0
 public void TestEnginePreparation()
 {
     TemplateService templateService = new TemplateService();
     templateService.PrepareEngine += new System.Action<Jint.Engine>(templateService_PrepareEngine);
     Assert.AreEqual("pwet", templateService.Process("<% write('pwet'); %>"));
     templateService = new TemplateService(TemplateMode.HtmlEscaped);
     templateService.PrepareEngine += new System.Action<Jint.Engine>(templateService_PrepareEngine);
     Assert.AreEqual("pwet", templateService.Process("&lt;% write2('pwet'); %&gt;"));
 }
        public void Issue11_TemplateServiceShouldCompileModellessTemplate()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello World</h1>";

                service.Compile(template, null, "issue11");
            }
        }
        protected override async Task OnExecute()
        {
            var dc = GetDatacenter(required: true);
            var service = dc.GetService(Service);
            if (service == null)
            {
                await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoSuchService, Service, dc.FullName);
                return;
            }

            // Get the config template for this service
            if (dc.Environment.ConfigTemplates == null)
            {
                await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplateSource, dc.Environment.FullName);
            }
            else
            {
                if (!String.Equals(dc.Environment.ConfigTemplates.Type, FileSystemConfigTemplateSource.AbsoluteAppModelType, StringComparison.OrdinalIgnoreCase))
                {
                    await Console.WriteErrorLine(Strings.Config_GenerateCommand_UnknownConfigTemplateSourceType, dc.Environment.ConfigTemplates.Type);
                }
                var configSource = new FileSystemConfigTemplateSource(dc.Environment.ConfigTemplates.Value);
                var configTemplate = configSource.ReadConfigTemplate(service);
                if (String.IsNullOrEmpty(configTemplate))
                {
                    await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplate, service.FullName);
                }
                else
                {
                    var secrets = await GetEnvironmentSecretStore(Session.CurrentEnvironment);

                    // Render the template
                    var engine = new TemplateService(new TemplateServiceConfiguration()
                    {
                        BaseTemplateType = typeof(ConfigTemplateBase),
                        Language = Language.CSharp
                    });
                    await Console.WriteInfoLine(Strings.Config_GenerateCommand_CompilingConfigTemplate, service.FullName);
                    engine.Compile(configTemplate, typeof(object), "configTemplate");

                    await Console.WriteInfoLine(Strings.Config_GenerateCommand_ExecutingTemplate, service.FullName);
                    string result = engine.Run("configTemplate", new ConfigTemplateModel(secrets, service), null);

                    // Write the template
                    if (String.IsNullOrEmpty(OutputFile))
                    {
                        await Console.WriteDataLine(result);
                    }
                    else
                    {
                        File.WriteAllText(OutputFile, result);
                        await Console.WriteInfoLine(Strings.Config_GenerateCommand_GeneratedConfig, OutputFile);
                    }
                }
            }
        }
Beispiel #15
0
        public string Parse()
        {
            TemplateService templateService = new TemplateService();
            string templateName = "TestTemplate";
            string body = "@model dynamic" + Environment.NewLine + "<html>Hello, @Model.CustomerName!</html>";
            dynamic model = new { CustomerName = "Girish" };

            var result = templateService.Parse(body, model, null, templateName);
            return result;
        }
 public void TestFixtureSetUp()
 {
     var templateService = new TemplateService();
     var embeddedEmailResourceProvider = new EmbeddedEmailResourceProvider(
         typeof(SimpleEmailModel).Assembly,
         "Email.RazorTemplates",
         "Email.Images",
         "en-AU");
     _emailTemplateInitializer = new RazorEmailTemplateInitializer(embeddedEmailResourceProvider, templateService);
     _emailFormatter = new RazorEmailFormatter(templateService, _emailTemplateInitializer);
 }
Beispiel #17
0
 public KompService(
     ComponentService componentService,
     ConfigService configService,
     TemplateService templateService,
     AddOnService addOnService)
 {
     _componentService = componentService;
     _configService    = configService;
     _templateService  = templateService;
     _addOnService     = addOnService;
 }
Beispiel #18
0
 public void TestScriptTransformation()
 {
     TemplateService templateService = new TemplateService(TemplateMode.HtmlEscaped);
     templateService.TransformFoundScript += new Func<string, string>(templateService_TransformFoundScript);
     Assert.AreEqual("pwet", templateService.Process("&lt;% if(1&lt;2) write(&quot;pwet&quot;); %&gt;"));
     //Assert.AreEqual("pwet", templateService.Process("&lt;% if(1&lt;2) %&lt; &lt;%= 'pwet' %&gt;"));
     templateService = new TemplateService(TemplateMode.Standard);
     templateService.TransformFoundScript += new Func<string, string>(templateService_TransformFoundScript);
     Assert.AreEqual("pwet", templateService.Process("<% if(2>1) { %><%= 'pwet' %><% } %><% else if(2>1) { %><%= 'pwic' %><% } %>"));
     Assert.AreEqual("pwic", templateService.Process("<% if(1>2) { %><%= 'pwet' %><% } %><% else if(2>1) { %><%= 'pwic' %><% } %>"));
 }
        public ActionResult Edit(int id)
        {
            var service  = new TemplateService();
            var template = service.GetTemplateById(id);
            var model    = new TemplateEdit
            {
                TemplateId = template.Id,
                Name       = template.Name,
            };

            return(View(model));
        }
Beispiel #20
0
 public TemplateController(
     ILogger <AdminController> logger,
     IIdentityResolver identityResolver,
     TemplateService templateService,
     IHypervisorService podService,
     IHubContext <TopologyHub, ITopoEvent> hub
     ) : base(logger, identityResolver)
 {
     _templateService = templateService;
     _pod             = podService;
     _hub             = hub;
 }
Beispiel #21
0
        // GET: Create
        public ActionResult Create()
        {
            var service   = new TemplateService();
            var templates = service.GetTemplates();
            List <SelectListItem> templateSelect = templates.Select(t => new SelectListItem {
                Value = t.Id.ToString(), Text = t.Name
            }).ToList();

            ViewBag.Templates = templateSelect;

            return(View());
        }
Beispiel #22
0
        public void TestFixtureSetUp()
        {
            var templateService = new TemplateService();
            var embeddedEmailResourceProvider = new EmbeddedEmailResourceProvider(
                typeof(SimpleEmailModel).Assembly,
                "Email.RazorTemplates",
                "Email.Images",
                "en-AU");

            _emailTemplateInitializer = new RazorEmailTemplateInitializer(embeddedEmailResourceProvider, templateService);
            _emailFormatter           = new RazorEmailFormatter(templateService, _emailTemplateInitializer);
        }
        public void TemplateService_CanParseMultipleTemplatesInParallel_WitNoModels()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello World</h1>";
                var templates = Enumerable.Repeat(template, 10);

                var results = service.ParseMany(templates, true);

                Assert.That(templates.SequenceEqual(results), "Rendered templates do not match expected.");
            }
        }
        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));
            }
        }
        public void TemplateService_CanParseMultipleTemplatesInParallel_WitNoModels()
        {
            using (var service = new TemplateService())
            {
                const string template  = "<h1>Hello World</h1>";
                var          templates = Enumerable.Repeat(template, 10);

                var results = service.ParseMany(templates, null, null, null, true);

                Assert.That(templates.SequenceEqual(results), "Rendered templates do not match expected.");
            }
        }
        protected override async void Execute()
        {
            EnsureApplicationResources();
            TelemetryService.Instance.Init();

            //check for new version
            await TelemetryService.Instance.CheckForUpdates(true);

            TelemetryService.Instance.SendCrashes(false);
            var pathToTempFolder = CreateTempPackageFolder();

            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Filter = @"Transit Project Package Files (*.ppf)|*.ppf";
                var dialogResult = fileDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    var path = fileDialog.FileName;

                    var packageService = new PackageService();
                    var package        = await packageService.OpenPackage(path, pathToTempFolder);

                    var templateService = new TemplateService();
                    var templateList    = templateService.LoadProjectTemplates();


                    var packageModel = new PackageModel
                    {
                        Name            = package.Name,
                        Description     = package.Description,
                        StudioTemplates = templateList,
                        SourceLanguage  = package.SourceLanguage,
                        TargetLanguage  = package.TargetLanguage,
                        SourceFiles     = package.SourceFiles,
                        TargetFiles     = package.TargetFiles
                    };
                    StarTransitMainWindow window = new StarTransitMainWindow(packageModel);
                    window.ShowDialog();
                }
            }
            catch (Exception e)
            {
                TelemetryService.Instance.HandleException(e);
            }
            finally
            {
                if (Directory.Exists(pathToTempFolder))
                {
                    Directory.Delete(pathToTempFolder, true);
                }
            }
        }
        public void TemplateService_CanParseSimpleTemplate_WithNoModel()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello World</h1>";
                const string expected = template;

                string result = service.Parse(template, null, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void TemplateService_CanParseTildeInTemplate_UsingHtmlEncoding()
        {
            using (var service = new TemplateService()) {
                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);
            }
        }
Beispiel #29
0
        static Render()
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType = typeof(HtmlTemplateBase<>)
            };

            var service = new TemplateService(config);
            Razor.SetTemplateService(service);
            Razor.Compile(Resources.FormattedSingleFile(), "singleFile");
            Razor.Compile(Resources.Directory(), "directory");
        }
        public static void SendEmail(SubscriptionResult Subscription, IApplicationConfigRepository applicationConfigRepository, IEmailTemplateRepository emailTemplateRepository)
        {
            MailMessage mail     = new MailMessage();
            string      FromMail = applicationConfigRepository.GetValuefromApplicationConfig("SMTPFromEmail");
            string      password = applicationConfigRepository.GetValuefromApplicationConfig("SMTPPassword");
            string      username = applicationConfigRepository.GetValuefromApplicationConfig("SMTPUserName");
            string      Subject  = emailTemplateRepository.GetSubject(Subscription.SaasSubscriptionStatus.ToString());
            bool        smtpSsl  = bool.Parse(applicationConfigRepository.GetValuefromApplicationConfig("SMTPSslEnabled"));

            mail.From = new MailAddress(FromMail);

            mail.Subject = Subject;

            string body = TemplateService.ProcessTemplate(Subscription, emailTemplateRepository, applicationConfigRepository);

            mail.Body       = body;
            mail.IsBodyHtml = true;
            if (!string.IsNullOrEmpty(emailTemplateRepository.GetToRecipients(Subscription.SaasSubscriptionStatus.ToString())))
            {
                string[] ToEmails = (emailTemplateRepository.GetToRecipients(Subscription.SaasSubscriptionStatus.ToString())).Split(';');
                foreach (string Multimailid in ToEmails)
                {
                    mail.To.Add(new MailAddress(Multimailid));
                }
            }

            if (!string.IsNullOrEmpty(emailTemplateRepository.GetCCRecipients(Subscription.SaasSubscriptionStatus.ToString())))
            {
                string[] CcEmails = (emailTemplateRepository.GetCCRecipients(Subscription.SaasSubscriptionStatus.ToString())).Split(';');
                foreach (string Multimailid in CcEmails)
                {
                    mail.CC.Add(new MailAddress(Multimailid));
                }
            }

            if (!string.IsNullOrEmpty(emailTemplateRepository.GetBccRecipients(Subscription.SaasSubscriptionStatus.ToString())))
            {
                string[] BccEmails = (emailTemplateRepository.GetBccRecipients(Subscription.SaasSubscriptionStatus.ToString())).Split(';');
                foreach (string Multimailid in BccEmails)
                {
                    mail.Bcc.Add(new MailAddress(Multimailid));
                }
            }
            SmtpClient smtp = new SmtpClient();

            smtp.Host = applicationConfigRepository.GetValuefromApplicationConfig("SMTPHost");
            smtp.Port = int.Parse(applicationConfigRepository.GetValuefromApplicationConfig("SMTPPort"));
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new NetworkCredential(
                username, password);
            smtp.EnableSsl = smtpSsl;
            smtp.Send(mail);
        }
        public void TemplateService_CanParseSimpleTemplate_WithNoModel()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello World</h1>";
                const string expected = template;

                string result = service.Parse(template);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Beispiel #32
0
        public void Issue27_StreamLiningTheITemplateServiceApi_CreateTemplates()
        {
            string[] razorTemplates;
            Type[]   templateTypes;
            int      index;

            using (var service = new TemplateService())
            {
                // Success case
                razorTemplates = new string[] { "Template1", "Template2", "Template3" };
                templateTypes  = new Type[] { null, null, null };
                IEnumerable <ITemplate> instances = service.CreateTemplates(razorTemplates, templateTypes, null, false);

                index = 0;
                foreach (ITemplate instance in instances)
                {
                    string expected = razorTemplates[index];
                    string result   = service.Run(instance, null);
                    Assert.That(result == expected, "Result does not match expected: " + result);
                    index++;
                }

                // No razorTemplates or templateTypes provided
                Assert.Throws <ArgumentException>(() =>
                {
                    service.CreateTemplates(null, null, null, false);
                });

                // Unbalanced razorTemplates/templateTypes (templateTypes to small)
                Assert.Throws <ArgumentException>(() =>
                {
                    razorTemplates = new string[] { "Template1", "Template2", "Template3" };
                    templateTypes  = new Type[] { null, null };
                    service.CreateTemplates(razorTemplates, templateTypes, null, false);
                });

                // Unbalanced razorTemplates/templateTypes (templateTypes too large)
                Assert.Throws <ArgumentException>(() =>
                {
                    razorTemplates = new string[] { "Template1", "Template2", "Template3" };
                    templateTypes  = new Type[] { null, null, null, null };
                    service.CreateTemplates(razorTemplates, templateTypes, null, false);
                });

                // Unbalanced razorTemplates/templateTypes (razorTemplates and templateTypes are NULL)
                Assert.Throws <ArgumentException>(() =>
                {
                    razorTemplates = new string[] { "Template1", "Template2", null };
                    templateTypes  = new Type[] { null, null, null };
                    service.CreateTemplates(razorTemplates, templateTypes, null, false);
                });
            }
        }
Beispiel #33
0
        /// <summary>
        /// Configures the templating engine.
        /// </summary>
        private static void Configure()
        {
            var config = RazorEngineConfigurationSection.GetConfiguration();

            if (config != null)
            {
                if (!string.IsNullOrWhiteSpace(config.Factory))
                {
                    SetCompilerServiceFactory(config.Factory);
                }
                else
                {
                    CompilerServiceFactory = new DefaultCompilerServiceFactory();
                }

                if (config.TemplateServices.Count > 0)
                {
                    string @default = string.IsNullOrWhiteSpace(config.TemplateServices.Default)
                                          ? null
                                          : config.TemplateServices.Default;

                    foreach (TemplateServiceConfigurationElement serviceConfig in config.TemplateServices)
                    {
                        string name    = serviceConfig.Name;
                        var    service = ConfigurationServices.CreateTemplateService(serviceConfig);;
                        ConfigurationServices.AddNamespaces(service, config.Namespaces);

                        if (name == @default)
                        {
                            DefaultTemplateService = service;
                        }

                        Services.Add(name, service);
                    }
                }

                if (DefaultTemplateService == null)
                {
                    DefaultTemplateService = new TemplateService(CompilerServiceFactory.CreateCompilerService());
                    ConfigurationServices.AddNamespaces(DefaultTemplateService, config.Namespaces);
                }

                if (!string.IsNullOrWhiteSpace(config.Activator))
                {
                    DefaultTemplateService.SetActivator(ConfigurationServices.CreateInstance <IActivator>(config.Activator));
                }
            }
            else
            {
                ConfigureDefault();
            }
        }
        public void ReplaceText_OneVariable()
        {
            string baseTemplate  = "Hello $name$";
            var    dictVariables = new Dictionary <string, string>
            {
                { "name", "Denis" }
            };
            string expected = "Hello Denis";

            string result = TemplateService.ApplyTextTemplateAsync(baseTemplate, dictVariables).Result;

            Assert.Equal(expected, result);
        }
        public void TemplateService_CanParseSimpleTemplate_WithAnonymousModel()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Model.Forename</h1>";
                const string expected = "<h1>Hello Matt</h1>";

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

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Beispiel #36
0
        public void FillEnumValueTemplate_ValuesGiven_TemplateFilledWithValues()
        {
            _internalStorage.GetEmbeddedResource("TypeGen.Core.Templates.EnumValue.tpl")
            .Returns("$tg{name} | $tg{number}");
            var templateService = new TemplateService(_internalStorage)
            {
                GeneratorOptions = new GeneratorOptions()
            };

            string actual = templateService.FillEnumValueTemplate("a", 42);

            Assert.Equal("a | 42", actual);
        }
Beispiel #37
0
        public static string GenerateOutput(ExpandoObject model, string template)
        {
            var config = new FluentTemplateServiceConfiguration(
                c => c.WithEncoding(RazorEngine.Encoding.Raw));

            string result;
            using (var service = new TemplateService(config))
            {
                result = service.Parse(template, model);
            }

            return result;
        }
Beispiel #38
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));
            }
        }
Beispiel #39
0
        public void FillClassPropertyTemplate_ValuesGiven_TemplateFilledWithValues()
        {
            _internalStorage.GetEmbeddedResource("TypeGen.Core.Templates.ClassProperty.tpl")
            .Returns("$tg{accessor} | $tg{name} | $tg{type}");
            var templateService = new TemplateService(_internalStorage)
            {
                GeneratorOptions = new GeneratorOptions()
            };

            string actual = templateService.FillClassPropertyTemplate("a", "B", "c");

            Assert.Equal("a | B | c", actual);
        }
Beispiel #40
0
        public void FillIndexExportTemplate_ValuesGiven_TemplateFilledWithValues()
        {
            _internalStorage.GetEmbeddedResource("TypeGen.Core.Templates.IndexExport.tpl")
            .Returns("$tg{filename}");
            var templateService = new TemplateService(_internalStorage)
            {
                GeneratorOptions = new GeneratorOptions()
            };

            string actual = templateService.FillIndexExportTemplate("a");

            Assert.Equal("a", actual);
        }
Beispiel #41
0
        public void FillImportTemplate_ValuesGiven_TemplateFilledWithValues(string typeAlias, string expectedResult)
        {
            _internalStorage.GetEmbeddedResource("TypeGen.Core.Templates.Import.tpl")
            .Returns("$tg{name} | $tg{aliasText} | $tg{path}");
            var templateService = new TemplateService(_internalStorage)
            {
                GeneratorOptions = new GeneratorOptions()
            };

            string actual = templateService.FillImportTemplate("a", typeAlias, "c");

            Assert.Equal(expectedResult, actual);
        }
        public void RazorEngineHost_SupportsModelSpan_UsingCSharpCodeParser()
        {
            using (var service = new TemplateService())
            {
                const string template = "@model List<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);
            }
        }
        public void TemplateBase_CanUseRawOutput_WithHtmlEncoding()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Raw(Model.Name)</h1>";
                const string expected = "<h1>Hello <</h1>";

                var model = new { Name = "<" };
                string result = service.Parse(template, model);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void TemplateService_CanParseSimpleTemplate_WithIteratorModel()
        {
            using (var service = new TemplateService())
            {
                const string template = "@foreach (var i in Model) { @i }";
                const string expected = "One Two Three";

                var    model  = CreateIterator("One ", "Two ", "Three");
                string result = service.Parse(template, model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Beispiel #45
0
        public void GetAvailableTemplates_returnsTemplates()
        {
            var templates = new TemplateService(_loggerFactory.CreateLogger <TemplateService>())
                            .GetAvailableTemplates();

            Assert.NotNull(templates);
            Assert.NotEmpty(templates);

            Assert.Contains(templates, x => x.ShortName == "Steeltoe-WebApi" && x.TemplateVersion == TemplateVersion.V2);
            Assert.Contains(templates, x => x.ShortName == "Steeltoe-WebApi" && x.TemplateVersion == TemplateVersion.V3);
            Assert.Contains(templates, x => x.ShortName == "Steeltoe-React" && x.TemplateVersion == TemplateVersion.V2);
            Assert.Contains(templates, x => x.ShortName == "Steeltoe-React" && x.TemplateVersion == TemplateVersion.V3);
        }
Beispiel #46
0
        public void Generic_settings_from_parameter_names_should_be_valid()
        {
            var templates = TemplateService.Get();

            foreach (var template in templates)
            {
                var validSettings = template.ParameterNames
                                    .ToDictionary(p => p, p => (decimal)10);

                var validateResult = TemplateService.Validate(template.Id, validSettings);
                Assert.True(validateResult.IsSuccess);
            }
        }
Beispiel #47
0
        public void FillClassTemplate_ValuesGiven_TemplateFilledWithValues()
        {
            _internalStorage.GetEmbeddedResource("TypeGen.Core.Templates.Class.tpl")
            .Returns("$tg{imports} | $tg{name} | $tg{extends} | $tg{properties} | $tg{customHead} | $tg{customBody}");
            var templateService = new TemplateService(_internalStorage)
            {
                GeneratorOptions = new GeneratorOptions()
            };

            string actual = templateService.FillClassTemplate("a", "B", "c", "D", "e", "F");

            Assert.Equal("a | B | c | D | e | F", actual);
        }
        public void Issue16_LastNullValueShouldReturnEmptyString()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Model.Person.Forename</h1>";
                const string expected = "<h1>Hello </h1>";

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

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Beispiel #49
0
        public static string RenderTemplate(string templateName, object model = null, DynamicViewBag viewBag = null)
        {
            var templateFolderPath       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Views\Email");
            var templateService          = new TemplateService();
            var confirmationTemplatePath = Path.Combine(templateFolderPath, templateName);

            return(templateService.Parse(
                       File.ReadAllText(confirmationTemplatePath),
                       model,
                       viewBag,
                       "TemplateCache"
                       ));
        }
        public void TemplateBase_CanUseRawOutput_WithHtmlEncoding()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Raw(Model.Name)</h1>";
                const string expected = "<h1>Hello <</h1>";

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

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void ReplaceText_NoVariables()
        {
            string baseTemplate  = "Hello!";
            var    dictVariables = new Dictionary <string, string>
            {
            };

            string expected = "Hello!";

            string result = TemplateService.ApplyTextTemplateAsync(baseTemplate, dictVariables).Result;

            Assert.Equal(expected, result);
        }
Beispiel #52
0
        public void TemplateService_ShouldEnableNullableValueTypes()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Model.Number</h1>";
                const string expected = "<h1>Hello </h1>";

                var    model  = new { Number = (int?)null };
                string result = service.Parse(template, model, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public ActionResult Edit(int id)
        {
            var service  = new TemplateService();
            var property = service.GetTemplatePropById(id);
            var model    = new TemplatePropEdit
            {
                PropertyId   = property.Id,
                PropertyName = property.PropertyName,
                TemplateId   = property.TemplateId
            };

            return(View(model));
        }
        public void ReplaceText_NumberOfVariablesDoesNotMatch_MoreVariables()
        {
            string baseTemplate = "Hello $name$. Your account balance is $$balance$. Thanks $name$!";

            var dictVariables = new Dictionary <string, string>
            {
                { "name", "Denis" }
            };

            Assert.ThrowsAsync <ArgumentException>(() =>
                                                   TemplateService.ApplyTextTemplateAsync(baseTemplate, dictVariables)
                                                   );
        }
        public void TemplateService_CanParseSimpleTemplate_WithAnonymousModel()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @Model.Forename</h1>";
                const string expected = "<h1>Hello Matt</h1>";

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

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void TemplateService_CanParseSimpleHelperTemplate_UsingHtmlEncoding()
        {
            using (var service = new TemplateService())
            {
                const string template = "<h1>Hello @NameHelper()</h1>@helper NameHelper() { @Model.String }";
                const string expected = "<h1>Hello Matt &amp; 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);
            }
        }
        public void Issue7_ViewBagShouldPersistThroughLayout()
        {
            using (var service = new TemplateService())
            {
                const string layoutTemplate = "<h1>@ViewBag.Title</h1>@RenderSection(\"Child\")";
                const string childTemplate = "@{ Layout =  \"Parent\"; ViewBag.Title = \"Test\"; }@section Child {}";

                service.Compile(layoutTemplate, null, "Parent");

                string result = service.Parse(childTemplate, null, null, null);

                Assert.That(result.StartsWith("<h1>Test</h1>"));
            }
        }
        public void TemplateBase_CanRenderWithInclude_SimpleInclude()
        {
            using (var service = new TemplateService())
            {
                const string child = "<div>Content from child</div>";
                const string template = "@Include(\"Child\")";
                const string expected = "<div>Content from child</div>";

                service.GetTemplate(child, "Child");
                string result = service.Parse(template);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public void FluentTemplateServiceConfiguration_CanConfigureTemplateService_WithSpecificCodeLanguage()
        {
            var config = new FluentTemplateServiceConfiguration(
                c => c.WithCodeLanguage(Language.VisualBasic));

            using (var service = new TemplateService(config))
            {
                const string template = "@Code Dim name = \"Matt\" End Code\n@name";
                const string expected = "\nMatt";

                string result = service.Parse(template, null, null, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
        public string BuildContentResult(string page, string id)
        {
            using (var service = new TemplateService())
            {
                // get the top level razor template, e.g. "product"
                // equivalent of "product.cshtml"
                var content = GetContent(page);
                var data = GetData(id);

                ProcessContent(content, service, data);
                var result = service.Parse(content, data, null, page);

                return result;
            }
        }