Esempio n. 1
0
        public EmailSender(IConfiguration configuration,
                           ILogger <EmailSender> logger,
                           IHttpContextAccessor httpContextAccessor,
                           IHostingEnvironment hostEnvironment)
        {
            _httpContextAccessor = httpContextAccessor;
            _configuration       = configuration;
            _logger = logger;
            _client = new SendGridClient(_configuration["SENDGRID_API_KEY"]);

            if (_configuration.GetSection("Email") == null)
            {
                throw new Exception("Configuration for Email not found");
            }

            _maxEmailAttempts = Convert.ToInt32(_configuration["Email:MaxAttempts"] ?? "3");
            _fromEmail        = _configuration["Email:FromEmail"];
            _fromName         = _configuration["Email:FromName"];

            string templatePath = Path.Combine(hostEnvironment.WebRootPath, "EmailTemplates");

            _engine = new RazorLightEngineBuilder()
                      .UseFilesystemProject(templatePath)
                      .UseMemoryCachingProvider()
                      .Build();
        }
Esempio n. 2
0
        private async Task NotifyUser(SummaryViewModel summary, RazorLightEngine razor, SmtpClient smtpClient)
        {
            if (!summary.Users.Any())
            {
                Logger.Warn("Not sending user notification, no users to notify");
                return;
            }

            string subjectTemplate = File.ReadAllText(Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, "Views", "UserSubject", "Template.cshtml"));
            string bodyTemplate    = File.ReadAllText(Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, "Views", "UserBody", "Template.cshtml"));

            ExpandoObject viewBag = new { SonarUrl }.ToExpando();

            foreach (UserViewModel model in summary.Users)
            {
                if (IgnoredRecipients.Contains(model.User.Key) || (RecipientFilter.Any() && !RecipientFilter.Contains(model.User.Key)))
                {
                    Logger.Info($"Not sending mail to: {model.User.Key}, recipient ignored");
                    continue;
                }

                await DoSendMessage(
                    smtpClient : smtpClient,
                    recipient : model.User.EmailAddress,
                    subject : (await razor.CompileRenderStringAsync("user-subject", subjectTemplate, model, viewBag).OnAnyThread()).Trim(),
                    message : (await razor.CompileRenderStringAsync("user-body", bodyTemplate, model, viewBag).OnAnyThread()).Trim()).OnAnyThread();
            }
        }
Esempio n. 3
0
        public void Allow_Null_CachingProvider()
        {
            var engine = new RazorLightEngine(new RazorLightOptions(), new Mock <ITemplateFactoryProvider>().Object, cachingProvider: null);

            Assert.NotNull(engine);
            Assert.Null(engine.TemplateCache);
        }
Esempio n. 4
0
 public DocumentationRenderer()
 {
     this.engine = new RazorLightEngineBuilder()
                   .UseEmbeddedResourcesProject(typeof(DocumentationRenderer))
                   .UseMemoryCachingProvider()
                   .Build();
 }
Esempio n. 5
0
 public RazorTemplateResolver(string resourcePath)
 {
     mEngine = new RazorLightEngineBuilder()
               .UseFilesystemProject(resourcePath)
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 6
0
 public RazorRenderer()
 {
     _engine = new RazorLightEngineBuilder()
               .UseEmbeddedResourcesProject(typeof(IKuvert))
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 7
0
 public ViewAsPdf(string viewsPath = null)
 {
     _engine = new RazorLightEngineBuilder()
               .UseFilesystemProject(viewsPath)
               .UseMemoryCachingProvider()
               .Build();
 }
        public async static Task Main(string[] args)
        {
            string     view  = "Views.EmbedEmail.cshtml";
            EmailModel model = GetModel();
            RazorViewToStringRenderer razor      = GetRazorRenderer();
            RazorLightEngine          razorLight = GetRazorLightRenderer();
            Stopwatch razorStopwatch             = new Stopwatch();
            Stopwatch razorLightStopwatch        = new Stopwatch();
            IEnumerable <Task <string> > tasks;

            for (int i = 0; i < Batches; i++)
            {
                razorStopwatch.Start();
                tasks = Enumerable.Range(0, NumberOfEmails / Batches)
                        .Select(_ => razor.Render(view, model));
                await Task.WhenAll(tasks);

                razorStopwatch.Stop();


                razorLightStopwatch.Start();
                tasks = Enumerable.Range(0, NumberOfEmails / Batches)
                        .Select(_ => razorLight.CompileRenderAsync(view, model));
                await Task.WhenAll(tasks);

                razorLightStopwatch.Stop();
            }
        }
Esempio n. 9
0
        /// <summary>
        /// ソースを生成する
        /// </summary>
        /// <param name="model">モデル</param>
        /// <param name="engine">エンジン</param>
        /// <returns></returns>
        private async Task <List <dynamic> > GenerateSource(dynamic model, RazorLightEngine engine)
        {
            var generatedSource = new List <dynamic>();

            for (int i = 0; i < model.RootList.Count; i++)
            {
                // 変数入れる
                model.General.Index = i.ToString();

                // テンプレート読み込み
                var template = GetTemplate((string)model.RootList[i].RazorTemplate);

                // ソース生成
                // 同じキーを指定すると登録したスクリプトを使いまわすことが出来るが、何故か2回目以降Unicodeにされるので毎回違うキーを使う。
                var name = $"{model.RootList[i].Name + i}";
                try
                {
                    generatedSource.Add(await engine.CompileRenderStringAsync(name, template, model));
                }
                catch (Exception e)
                {
                    // 生成で何かエラーがあったらここ。
                    throw e;
                }
            }

            return(generatedSource);
        }
Esempio n. 10
0
 public RazorRenderer(RazorLightProject project)
 {
     _engine = new RazorLightEngineBuilder()
               .UseProject(project)
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 11
0
        public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity)
        {
            var template = activity.GetOptionValue("Template");

            if (engine == null)
            {
                engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(AppDomain.CurrentDomain.GetData("ContentRootPath").ToString() + "\\App_Data")
                         .UseMemoryCachingProvider()
                         .Build();
            }

            var model = CleanJObject(activity);

            string result = "";

            var cacheResult = engine.TemplateCache.RetrieveTemplate(template);

            if (cacheResult.Success)
            {
                result = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model);
            }
            else
            {
                result = await engine.CompileRenderAsync(template, model);
            }

            activity.Output.Data = JObject.Parse(result);
        }
Esempio n. 12
0
 public RazorLightMessageProvider(IEmailTemplateConfiguration templateConfiguration)
 {
     _razorEngine = new RazorLightEngineBuilder()
                    .UseFilesystemProject(templateConfiguration.TemplateFolder)
                    .UseMemoryCachingProvider()
                    .Build();
 }
Esempio n. 13
0
 public TemplatesService(string templatePath)
 {
     engine = new RazorLightEngineBuilder()
              .UseFilesystemProject(templatePath)
              .UseMemoryCachingProvider()
              .Build();
 }
 public RazorTemplateEngine()
 {
     engine = new RazorLightEngineBuilder()
              .UseProject(new EmbeddedRazorProject(Assembly.GetExecutingAssembly()))
              .UseMemoryCachingProvider()
              .Build();
 }
Esempio n. 15
0
 public RazorRenderer(Type embeddedResRootType)
 {
     _engine = new RazorLightEngineBuilder()
               .UseEmbeddedResourcesProject(embeddedResRootType)
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 16
0
 public RazorRenderer(string root = null)
 {
     _engine = new RazorLightEngineBuilder()
               .UseFileSystemProject(root ?? Directory.GetCurrentDirectory())
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 17
0
    /// <summary>
    /// create or over write html file
    /// </summary>
    /// <param name="engine">RazorLightEngin Instance</param>
    /// <param name="cshtmlPath">cshtml template file</param>
    /// <param name="outputDir">out put directory</param>
    public async Task CreateOrOverWrite(RazorLightEngine engine, string cshtmlPath, string outputDir)
    {
        string result = await engine.CompileRenderAsync(cshtmlPath, new { title = fileName, articleText = convertHtml });

        string htmlFilePath = HtmlFilePath(outputDir);

        Console.WriteLine($"[Generate] : {htmlFilePath}");

        // create directory if not exist
        string htmlFileDir = Path.GetDirectoryName(htmlFilePath);

        if (!Directory.Exists(htmlFileDir))
        {
            Directory.CreateDirectory(htmlFileDir);
        }

        // over write or create file
        if (File.Exists(htmlFilePath))
        {
            File.WriteAllText(htmlFilePath, result);
        }
        else
        {
            using (FileStream fs = File.Create(htmlFilePath))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(result);
                }
        }
    }
Esempio n. 18
0
 public ViewAsPdf()
 {
     _engine = new RazorLightEngineBuilder()
               .UseFilesystemProject(Directory.GetCurrentDirectory())
               .UseMemoryCachingProvider()
               .Build();
 }
Esempio n. 19
0
 public EmailService(string webRootPath)
 {
     this.MailKey       = System.Configuration.ConfigurationManager.AppSettings["emailKey"];
     this.FromEmail     = System.Configuration.ConfigurationManager.AppSettings["fromEmailAddress"];
     this.FromEmailName = System.Configuration.ConfigurationManager.AppSettings["fromEmailName"];
     this.WebRootPath   = webRootPath;
     this.RazorEngine   = RazorEngineSingleton.GetRazorEngine();
 }
Esempio n. 20
0
        public TemplateProcessor()
        {
            engine = new RazorLightEngineBuilder()
                     .UseMemoryCachingProvider()
                     .Build();

            md5 = MD5.Create();
        }
Esempio n. 21
0
 public BaseGenerator(GlobalConfiguration config)
 {
     _config = config;
     _engine = new RazorLightEngineBuilder()
               .UseFilesystemProject(_config.TemplatePath)
               .UseMemoryCachingProvider()
               .Build();
 }
        /// <summary>
        /// GraphTemplateManager
        /// </summary>
        /// <param name="graphTemplateRepository"></param>
        public GraphTemplateManager(IGraphTemplateRepository graphTemplateRepository)
        {
            this.graphTemplateRepository = graphTemplateRepository ?? throw new ArgumentNullException(nameof(graphTemplateRepository));

            Engine = new RazorLightEngineBuilder()
                     .UseMemoryCachingProvider()
                     .Build();
        }
Esempio n. 23
0
        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="logger">Для логирования событий.</param>
        public RazorTemplateEngine(ILogger <RazorTemplateEngine> logger)
        {
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            engine = new RazorLightEngineBuilder()
                     .UseMemoryCachingProvider()
                     .Build();
        }
Esempio n. 24
0
 public RazorLightContentTransformer()
 {
     m_RazorEngine = new RazorLightEngineBuilder()
                     .AddDefaultNamespaces(typeof(Site).Namespace)
                     .UseMemoryCachingProvider()
                     .UseEmbeddedResourcesProject(typeof(RazorLightContentTransformer))
                     .Build();
 }
Esempio n. 25
0
 public GraphToScriptConverter(Graph graph)
 {
     _graph          = graph;
     _templateEngine = new RazorLightEngineBuilder()
                       .UseMemoryCachingProvider()
                       .UseEmbeddedResourcesProject(typeof(GraphToScriptConverter).Assembly, "Templates.Script")
                       .Build();
 }
Esempio n. 26
0
        public RazorLightDemo()
        {
            _razorLightEngine = new RazorLightEngineBuilder()
                                .UseMemoryCachingProvider()
                                .Build();

            _template = TemplateManagement.Read("RazorLightDemo\\template.html");
        }
Esempio n. 27
0
        public HtmlRender()
        {
            var builder = new RazorLightEngineBuilder()
                          .UseEmbeddedResourcesProject(typeof(HtmlRender))
                          .UseMemoryCachingProvider();

            _engine = builder
                      .Build();
        }
Esempio n. 28
0
        public RazorGenerator()
        {
            engine = new RazorLightEngineBuilder()
                     .UseEmbeddedResourcesProject(GetType().Assembly)
                     .UseMemoryCachingProvider()
                     .Build();

            engine.CompileTemplateAsync(TemplateName).Wait();
        }
Esempio n. 29
0
        public RazorTemplateEngine(ILogger <RazorTemplateEngine>?logger = null)
        {
            _razorEngine = new RazorLightEngineBuilder()
                           .UseEmbeddedResourcesProject(typeof(Program))
                           .UseMemoryCachingProvider()
                           .Build();

            _logger = logger ?? NullLogger <RazorTemplateEngine> .Instance;
        }
Esempio n. 30
0
        public EmailService(IOptions <MailConfiguration> configuration, IHostingEnvironment env)
        {
            this.configuration = configuration;

            this.engine = new RazorLightEngineBuilder()
                          .UseFilesystemProject(env.ContentRootPath)
                          .UseMemoryCachingProvider()
                          .Build();
        }
 public TemplateEngine()
 {
     engine = new RazorLightEngine();
 }