Пример #1
0
        public async Task SendEmailsWithTemplate(string title, List <Subscriber> subscribers, Post model, string template)
        {
            var path = Path.Combine(
                _env.WebRootPath, "Templates/");

            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(path)
                         .UseMemoryCachingProvider()
                         .Build();

            string body = "";

            // send email to me to check what it looks like
            body = await engine.CompileRenderAsync(template, model);

            Execute("", title, body).Wait();

            if (subscribers.Count != 0)
            {
                // send to every subscriber email with template
                foreach (var sub in subscribers)
                {
                    body = await engine.CompileRenderAsync(template, model);

                    Execute(Regex.Replace(sub.Email, "%40", "@"), title, body).Wait();
                }
            }
        }
Пример #2
0
        private async void OnExecute()
        {
            try
            {
                Console.WriteLine($"Loading {SchemaFile}...");
                var schemaText = File.ReadAllText(SchemaFile);

                var mappings = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(ScalarMapping))
                {
                    mappings = ScalarMapping.Split(',').Select(s => s.Split('=')).ToDictionary(k => k[0], v => v[1]);
                }

                // parse into AST
                var typeInfo = SchemaCompiler.Compile(schemaText, mappings);

                Console.WriteLine($"Generating types in namespace {Namespace}, outputting to {ClientClassName}.cs");

                // pass the schema to the template
                var engine = new RazorLightEngineBuilder()
                             .UseEmbeddedResourcesProject(typeof(Program))
                             .UseMemoryCachingProvider()
                             .Build();

                var allTypes = typeInfo.Types.Concat(typeInfo.Inputs).ToDictionary(k => k.Key, v => v.Value);

                string result = await engine.CompileRenderAsync("types.cshtml", new
                {
                    Namespace  = Namespace,
                    SchemaFile = SchemaFile,
                    Types      = allTypes,
                    Enums      = typeInfo.Enums,
                    Mutation   = typeInfo.Mutation,
                    CmdArgs    = $"-n {Namespace} -c {ClientClassName} -m {ScalarMapping}"
                });

                Directory.CreateDirectory(OutputDir);
                File.WriteAllText($"{OutputDir}/GeneratedTypes.cs", result);

                result = await engine.CompileRenderAsync("client.cshtml", new
                {
                    Namespace       = Namespace,
                    SchemaFile      = SchemaFile,
                    Query           = typeInfo.Query,
                    Mutation        = typeInfo.Mutation,
                    ClientClassName = ClientClassName,
                });

                File.WriteAllText($"{OutputDir}/{ClientClassName}.cs", result);

                Console.WriteLine($"Done.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
        }
Пример #3
0
        static async Task Main(string[] args)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(Path.Combine(Directory.GetCurrentDirectory(), "Templates"))
                         .UseMemoryCachingProvider()
                         .Build();

            string result = await engine.CompileRenderAsync("Hello", new { Name = "John Doe" });

            Console.WriteLine(result);

            result = await engine.CompileRenderAsync("Hello", new { Name = "Jane Doe" });

            Console.WriteLine(result);
        }
Пример #4
0
        public async void SendEmail(EmailModel <Message> model, string viewPath)
        {
            string webRootPath     = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(contentRootPath)
                         .UseMemoryCachingProvider()
                         .Build();

            try
            {
                string result = await engine.CompileRenderAsync("/" + viewPath, model.Data);

                var mailModel = new EmailModel
                {
                    To                  = model.To,
                    Ccs                 = model.Ccs,
                    Subject             = model.Subject,
                    ExtraEmailAddresses = model.ExtraEmailAddresses,
                    Body                = "My Test body"
                };

                await _emailService.SendEmail(mailModel);
            }
            catch (Exception)
            {
            }
        }
        public Task SendModelConfirmationAsync(ApplicationUser user, UploadModelConfirmation model)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();


            string template = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "wwwroot", "Templates", "Emails", "Model", "ModelConfirmation.cshtml"));

            string result = engine.CompileRenderAsync("Confirmation", template, model).Result;

            List <Attachment> ATT = new List <Attachment>();

            foreach (var imglnk in model.ImageUrls)
            {
                string base64String = string.Empty;
                // Convert Image to Base64
                using (FileStream image = new FileStream(Path.Combine("wwwroot", "images", "ObjectImages", imglnk), FileMode.Open))
                {
                    MemoryStream ms = new MemoryStream();
                    image.CopyTo(ms);
                    Attachment a = new Attachment();
                    a.Content   = Convert.ToBase64String(ms.ToArray());
                    a.ContentId = imglnk;
                    a.Filename  = imglnk;
                    a.Type      = "image/jpeg";
                    ATT.Add(a);
                }
            }


            return(Execute(Options.SendGridKey, "Congrats On Your Upload!", result, user.Email, ATT));
        }
Пример #6
0
        private static async Task MainAsync()
        {
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            List <string> results = new List <string>();

            for (int i = 0; i < 100; i++)
            {
                ThreadPool.QueueUserWorkItem(async(s) =>
                {
                    try
                    {
                        results.Add(await engine.CompileRenderAsync("Views.Subfolder.go", null, null, null));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("J = " + j + " ============================\n" + e.StackTrace);
                    }

                    j++;
                });
            }

            while (j < 100)
            {
                Console.WriteLine("Waiting: " + j);
                Thread.Sleep(100);
            }

            Console.WriteLine("Finished");
        }
Пример #7
0
            public static string Compile(object model, string templateName)
            {
                var templatename = "Features\\Notification\\Templates\\" + templateName;

                Task <string> file = null;

                if (string.IsNullOrEmpty(templatename) || model == null)
                {
                    throw new Exception("Invalid Email compilation request.");
                }

                var templateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templatename);

                if (!File.Exists(templateFilePath))
                {
                    throw new Exception("File was not found");
                }

                var template = File.ReadAllText(templateFilePath);

                var engine = new RazorLightEngineBuilder()
                             .UseMemoryCachingProvider()
                             .Build();

                var templatekey = Guid.NewGuid().ToString();
                var t           = new Task(() =>
                {
                    file = engine.CompileRenderAsync(templatekey, template, model);
                });

                t.RunSynchronously();

                return(file.Result);
            }
Пример #8
0
        public async Task SendRegistrationEmailAsync(EmailRegistrationViewModel emailViewModel)
        {
            string emailTemplateFolderPath = Path.Combine(_environment.ContentRootPath, "EmailTemplates");

            string registrationEmailTemplatePath = Path.Combine(emailTemplateFolderPath, "Registration.cshtml");

            Console.WriteLine($"The registration email template path is: {registrationEmailTemplatePath}");

            RazorLightEngine engine = new RazorLightEngineBuilder()
                                      .UseFilesystemProject(emailTemplateFolderPath)
                                      .UseMemoryCachingProvider()
                                      .Build();

            string emailHtmlBody = await engine.CompileRenderAsync(registrationEmailTemplatePath, emailViewModel);

            MailMessage mailMessage = new MailMessage(
                _emailConfiguration.OutgoingEmailAddress,
                emailViewModel.UserEmailAddress,
                "Welcome to Bêjebêje",
                emailHtmlBody);

            mailMessage.IsBodyHtml = true;

            string operationIdentity = "Registration email";

            SendEmailAsync(mailMessage, operationIdentity);
        }
Пример #9
0
        static void Main(string[] args)
        {
            var md5     = "abcd";
            var content = @"
            @using Microsoft.AspNetCore.Html;
            @model RazorLightTest.Employee;
            <span>@(new HtmlString(Model.Name))</span>";

            var emp = new Employee()
            {
                Name = "<b>Partho</b>"
            };

            var razorEngine = new RazorLightEngineBuilder()
                              .UseMemoryCachingProvider()
                              .Build();

            var task = razorEngine.CompileRenderAsync(md5, content, emp);

            task.Wait();

            var result = task.Result;

            Console.WriteLine(result);
        }
Пример #10
0
        public async Task <string> Create(RequestArgs args, List <Hotel> hotels)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .UseFilesystemProject(Environment.CurrentDirectory + "/Report/Templates/")
                         .Build();                      // Creates the razor engine used for generation

            ReportViewModel model = new ReportViewModel // Initialise the view model with our supplied data for the template
            {
                SearchLocation = args.City,
                CheckIn        = args.CheckIn.ToShortDateString(),
                CheckOut       = args.CheckOut.ToShortDateString(),
                PersonAmount   = args.People,
                RoomAmount     = args.Rooms,
                Gathered       = DateTime.Now,
                Hotels         = hotels
            };

            string result = await engine.CompileRenderAsync("Template.cshtml", model); // Generate the HTMl with the template and viewmodel

            Directory.CreateDirectory(Environment.CurrentDirectory + "/Reports/");

            string filePath = Environment.CurrentDirectory + $"\\Reports\\{args.City}-{DateTime.Now.Hour}-{DateTime.Now.Minute}-{DateTime.Now.Second}-{DateTime.Now.Day}-{DateTime.Now.Month}-{DateTime.Now.Year}.html";

            File.WriteAllText(filePath, result);

            return(filePath);
        }
Пример #11
0
        /// <summary>
        /// Medhod for sending the Forgot Password Email
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task SendForgotPasswordEmailAsync(ApplicationUser user)
        {
            // Initiate forgot password
            user.ForgotPasswordInitiated = true;
            await _userManager.UpdateAsync(user);

            // Send email
            string passwordGenerationToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            passwordGenerationToken = HttpUtility.UrlEncode(passwordGenerationToken);
            string forgotPasswordLink = string.Format("{0}Home/ResetPassword?id={1}&token={2}", _stringConstants.WebsiteUrl, user.Id, passwordGenerationToken);

            string           path           = Path.Combine(Directory.GetCurrentDirectory(), "MailTemplates");
            RazorLightEngine engine         = new RazorLightEngineBuilder().UseFilesystemProject(path).UseMemoryCachingProvider().Build();
            string           resultFromFile = await engine.CompileRenderAsync("ForgotPasswordMail.cshtml", new ForgotPasswordMailAc { Name = user.Name, ForgotPasswordLink = forgotPasswordLink });

            _emailService.SendMail(new EmailMessage()
            {
                Content       = resultFromFile,
                Subject       = "Forgot Password",
                FromAddresses = new List <EmailAddress> {
                    new EmailAddress {
                        Address = _emailConfiguration.SmtpUsername, Name = "IMS SuperAdmin"
                    }
                },
                ToAddresses = new List <EmailAddress> {
                    new EmailAddress {
                        Address = user.Email, Name = user.Name
                    }
                }
            });
        }
Пример #12
0
        static void Main(string[] args)
        {
            var options = new DbContextOptionsBuilder <AppDbContext>()
                          .UseInMemoryDatabase(databaseName: "TestDatabase")
                          .Options;

            // Create and fill database with test data
            var db = new AppDbContext(options);

            FillDatabase(db);


            // Create engine that uses entityFramework to fetch templates from db
            // You can create project that uses your IRepository<T>
            var project = new EntityFrameworkRazorLightProject(db);
            var engine  = new RazorLightEngineBuilder().UseProject(project).Build();


            // As our key in database is integer, but engine takes string as a key - pass integer ID as a string
            string templateKey = "2";
            var    model       = new TestViewModel()
            {
                Name = "Johny", Age = 22
            };
            string result = engine.CompileRenderAsync(templateKey, model).Result;

            //Identation will be a bit fuzzy, as we formatted a string for readability
            Console.WriteLine(result);
            db.Dispose();
        }
Пример #13
0
        public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity)
        {
            var configuration       = (IConfiguration)AppDomain.CurrentDomain.GetData("Configuration");
            EmailRequestModel model = new EmailRequestModel();

            model.Subject     = activity.GetOptionValue("Subject");
            model.ToAddresses = activity.GetOptionValue("ToAddresses");
            model.Body        = activity.GetOptionValue("Body");
            model.Template    = activity.GetOptionValue("Template");
            model.Bcc         = activity.GetOptionValue("Bcc");
            model.Cc          = activity.GetOptionValue("Cc");

            if (!String.IsNullOrEmpty(model.Template))
            {
                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(AppDomain.CurrentDomain.GetData("ContentRootPath").ToString() + "\\App_Data")
                             .UseMemoryCachingProvider()
                             .Build();

                model.Body = await engine.CompileRenderAsync(model.Template, activity.Input.Data);
            }

            var ses = new SesEmailConfig
            {
                VerifiedEmail = configuration.GetSection("AWS:SESVerifiedEmail").Value,
                AWSSecretKey  = configuration.GetSection("AWS:AWSSecretKey").Value,
                AWSAccessKey  = configuration.GetSection("AWS:AWSAccessKey").Value
            };

            activity.Output.Data = await Send(model, ses);
        }
Пример #14
0
        public static void Main(string[] args)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(Program))
                         .UseMemoryCachingProvider()
                         .Build();

            WebHost.CreateDefaultBuilder(args)
            .Configure(app =>
            {
                app.Map("/articles.json", conf => {
                    app.Run(async(context) => {
                        context.Response.ContentType = "text/json; charset=utf-8";
                        var result = JsonConvert.SerializeObject(Articles());

                        await context.Response.WriteAsync(result);
                    });
                });

                app.Run(async(context) =>
                {
                    context.Response.ContentType = "text/html; charset=utf-8";

                    string result = await engine.CompileRenderAsync("Home.cshtml", Articles());

                    await context.Response.WriteAsync(result);
                });
            })
            .Build().Run();
        }
        public async Task <IActionResult> HtmlToPdfDemo([FromServices] INodeServices nodeServices)
        {
            var contentRootPath = HostingEnvironment.ContentRootPath;
            var templatePath    = Path.Combine(contentRootPath, "recursos\\PartidoTemplate.cshtml");

            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(contentRootPath)
                         .UseMemoryCachingProvider()
                         .Build();

            var model = new List <PartidoCompleto>();

            model.Add(new PartidoCompleto()
            {
                Fecha          = DateTime.Now,
                Local          = "Independiente",
                Visitante      = "River Plate",
                GolesLocal     = 0,
                GolesVisitante = 2
            });
            model.Add(new PartidoCompleto()
            {
                Fecha          = DateTime.Now,
                Local          = "Boca Juniors",
                Visitante      = "Cruzeiro",
                GolesLocal     = 3,
                GolesVisitante = 1
            });

            var html = await engine.CompileRenderAsync(templatePath, model);

            return(await ConvertirHtmlToPdf(nodeServices, html));
        }
Пример #16
0
        private async System.Threading.Tasks.Task <byte[]> CreateFilePDFAsync <T>(IReportsGrandGridView <T> groupedList)
        {
            if (!RunSetCommonValuesForExport)
            {
                throw new InvalidOperationException("You forgot run SetCommonValuesForExport() for set common values.");
            }

            var pdfBytesResult = new byte[0];

            #region Set root paths and give names for files.

            var fileNameWkhtmltopdf   = "wkhtmltopdf.exe";
            var fileNamePDFMarkUpView = "PDFMarkUpView.cshtml";

            var contentRootPath = _environment.ContentRootPath;

            var pathContentPDF            = $"{contentRootPath}\\Content\\PDF";
            var pathContentPDFCssStyle    = $"{pathContentPDF}\\Site.css";
            var pathContentPDFWkhtmltopdf = $"{pathContentPDF}\\{fileNameWkhtmltopdf}";

            var pathFileInfo = new FileInfo(pathContentPDFWkhtmltopdf);

            #endregion

            if (File.Exists(pathContentPDFWkhtmltopdf))
            {
                var pdfModel = new ReportsPDFCommonView(pathContentPDFCssStyle, GroupById, GetPeriodPDFCell())
                {
                    PDFGrandModel = CreateReportsGrandGridModel(groupedList)
                };

                #region Parse view.

                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(pathContentPDF)
                             .UseMemoryCachingProvider()
                             .Build();

                var htmlFromParsedViewRazorLight = await engine.CompileRenderAsync(fileNamePDFMarkUpView, pdfModel);

                var settings = new ConversionSettings(
                    pageSize: PageSize.A4,
                    orientation: PageOrientation.Landscape,
                    margins: new WkWrap.Core.PageMargins(5, 10, 5, 10),
                    grayscale: false,
                    lowQuality: false,
                    quiet: false,
                    enableJavaScript: true,
                    javaScriptDelay: null,
                    enableExternalLinks: true,
                    enableImages: true,
                    executionTimeout: null);

                pdfBytesResult = new HtmlToPdfConverter(pathFileInfo).ConvertToPdf(htmlFromParsedViewRazorLight, Encoding.UTF8, settings);

                #endregion
            }

            return(pdfBytesResult);
        }
Пример #17
0
        public async Task <string> ParseAsync <T>(string template, T model, bool isHtml = true)
        {
            var project = new InMemoryRazorLightProject();
            var engine  = new RazorLightEngineBuilder().UseMemoryCachingProvider().Build();

            return(await engine.CompileRenderAsync <T>(Guid.NewGuid().ToString(), template, model));
        }
        /// <summary>
        /// Render a view from a model by using the razor syntax
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="viewPath"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public string Render <T>(string viewPath, T model)
        {
            if (string.IsNullOrEmpty(viewPath))
            {
                throw new ArgumentNullException(nameof(viewPath));
            }

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var key    = $"{viewPath.ToLowerInvariant()}-{typeof(T)}";
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            var    cacheResult = engine.TemplateCache.RetrieveTemplate(key);
            string result;

            if (cacheResult.Success)
            {
                result = engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model).Result;
            }
            else
            {
                var template = string.Join("",
                                           GetViewContent(viewPath)
                                           .Where(l => !l.Contains(typeof(T).ToString())));//Remove @model in the template razor cshtml

                result = engine.CompileRenderAsync(key, template, model).Result;
            }

            return(result);
        }
Пример #19
0
        /// <summary>
        /// Render razor template using model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entry"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string RenderTemplate <T>(this LocalizationEntry entry, T model)
        {
            if (entry == null)
            {
                return(null);
            }
            if (model == null)
            {
                return(entry.Value);
            }

            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            var key = $"{entry?.LocalizationCollection?.LocalizationCategory?.Name}-{entry?.LocalizationCollection?.Name}-{entry?.LocalizationKey?.Name}";

            string result = engine
                            .CompileRenderAsync(key, entry.Value, model)
                            .GetAwaiter()
                            .GetResult();

            result = HttpUtility.HtmlDecode(result);

            return(result);
        }
Пример #20
0
        private async void SendMailAsync(ConfirmationViewModel model)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseFileSystemProject("C:/Users/SoMe0nE/Desktop/FlightManager/FlightManager/Web/Views")
                         .UseMemoryCachingProvider()
                         .Build();

            string result = await engine.CompileRenderAsync("Reservations/Email.cshtml", model);

            var email = new MailMessage();

            email.To.Add(new MailAddress(model.Email));
            email.From       = new MailAddress("*****@*****.**");
            email.Subject    = "Reservation details";
            email.Body       = result;
            email.IsBodyHtml = true;
            var smtp       = new SmtpClient();
            var credential = new NetworkCredential
            {
                UserName = "******",
                Password = "******"
            };

            smtp.Credentials = credential;
            smtp.Host        = "smtp.gmail.com";
            smtp.Port        = 587;
            smtp.EnableSsl   = true;
            await smtp.SendMailAsync(email);
        }
Пример #21
0
        public async Task SendForgotPasswordEmailAsync(EmailForgotPasswordViewModel emailViewModel)
        {
            string emailTemplateFolderPath = Path.Combine(_environment.ContentRootPath, "EmailTemplates");

            string reportEmailTemplatePath = Path.Combine(emailTemplateFolderPath, "ForgotPassword.cshtml");

            RazorLightEngine engine = new RazorLightEngineBuilder()
                                      .UseFilesystemProject(emailTemplateFolderPath)
                                      .UseMemoryCachingProvider()
                                      .Build();

            string emailHtmlBody = await engine.CompileRenderAsync(reportEmailTemplatePath, emailViewModel);

            MailMessage mailMessage = new MailMessage(
                emailViewModel.UserEmailAddress,
                _emailConfiguration.OutgoingEmailAddress,
                "Forgotten Password",
                emailHtmlBody);

            mailMessage.IsBodyHtml = true;

            string operationIdentity = "Forgotten password email";

            SendEmailAsync(mailMessage, operationIdentity);
        }
Пример #22
0
        public async Task <string> ParseAsync <T>(string template, T model, bool isHtml = true)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            return(await engine.CompileRenderAsync <T>(GetHashString(template), template, model));
        }
Пример #23
0
        public async Task Run(string [] args)
        {
            var ns               = args [0];
            var json             = GetJson(args [1]);
            var output_directory = args [2];
            var entities         = JsonConvert.DeserializeObject <List <Entity> > (json);
            var tpl_path         = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Templates");
            var engine           = new RazorLightEngineBuilder()
                                   .UseFileSystemProject(tpl_path)
                                   .UseMemoryCachingProvider()
                                   .Build();

            //var engine = EngineFactory.CreatePhysical (tpl_path);

            if (Directory.Exists(output_directory))
            {
                Directory.Delete(output_directory, true);
            }

            Directory.CreateDirectory(output_directory);
            Directory.CreateDirectory(Path.Combine(output_directory, "Entities"));
            Directory.CreateDirectory(Path.Combine(output_directory, "Repositories"));

            File.WriteAllText(Path.Combine(output_directory, "IUnitOfWork.cs"),
                              await engine.CompileRenderAsync("IUnitOfWork.cshtml", new { Namespace = ns }));
            File.WriteAllText(Path.Combine(output_directory, "UnitOfWork.cs"),
                              await engine.CompileRenderAsync("UnitOfWork.cshtml", new { Namespace = ns, Entities = entities }));
            File.WriteAllText(Path.Combine(output_directory, "Repositories", "RepositoryBase.cs"),
                              await engine.CompileRenderAsync("RepositoryBase.cshtml", new { Namespace = ns }));

            foreach (var entity in entities)
            {
                var model = new {
                    entity.Name,
                    entity.Table,
                    entity.Properties,
                    entity.Methods,
                    entity.PluralName,
                    Namespace = ns
                };

                File.WriteAllText(Path.Combine(output_directory, "Entities", entity.Name + ".cs"), await engine.CompileRenderAsync("Entity.cshtml", model));
                File.WriteAllText(Path.Combine(output_directory, "Repositories", "I" + entity.PluralName + "Repository.cs"), await engine.CompileRenderAsync("IRepository.cshtml", model));
                File.WriteAllText(Path.Combine(output_directory, "Repositories", entity.PluralName + "Repository.cs"), await engine.CompileRenderAsync("Repository.cshtml", model));
            }
        }
Пример #24
0
        /// <inheritdoc />
        public Task <string> GetBodyAsync()
        {
            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(GetType().Assembly)
                         .Build();

            return(engine.CompileRenderAsync(ViewNamespace, this));
        }
Пример #25
0
        public async Task Multiple_Simultaneous_Compilations_RaceCondition_Test()
        {
            var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);


            for (int i = 0; i < 1000; i++)
            {
                var engine = new RazorLightEngineBuilder()
                             .UseFileSystemProject(Path.Combine(path, "Assets", "Files"))
                             .Build();

                var model = new { };
                var t1    = Task.Run(async() => await engine.CompileRenderAsync("template1.cshtml", model));
                var t2    = Task.Run(async() => await engine.CompileRenderAsync("template2.cshtml", model));

                var result = await Task.WhenAll(t1, t2);
            }
        }
Пример #26
0
        private async Task <string> CreateTemplate(Contact contact)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject($@"{Directory.GetCurrentDirectory()}\Template")
                         .UseMemoryCachingProvider()
                         .Build();

            return(await engine.CompileRenderAsync("Email.cshtml", contact));
        }
Пример #27
0
        public View(string viewName, object model = null)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(API.env.ContentRootPath)
                         .UseMemoryCachingProvider()
                         .Build();

            result = engine.CompileRenderAsync($"Views/{viewName}.cshtml", model).Result;
        }
Пример #28
0
        private static string DoRazor(string name, string template, RestApiSpec model)
        {
            var engine = new RazorLightEngineBuilder()
                         .AddPrerenderCallbacks(t =>
            {
            }).Build();

            return(engine.CompileRenderAsync(name, template, model).GetAwaiter().GetResult());
        }
Пример #29
0
        public async Task <string> GetMessage(DumpMetainfo dumpInfo)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(SlackMessageViewModel))
                         .UseMemoryCachingProvider()
                         .Build();

            //var engine = new EngineFactory().ForEmbeddedResources(typeof(SlackMessageViewModel));
            return(await engine.CompileRenderAsync("SlackMessage", await GetMessageModel(dumpInfo)));
        }
Пример #30
0
        public async Task <string> Run(MainPostModel model)
        {
            var razorEngine = new RazorLightEngineBuilder()
                              .UseEmbeddedResourcesProject(typeof(Root).Assembly, GetEmbeddedResourceNamespace("SearchTargetEmbeddedMainPost.txt"))
                              .UseMemoryCachingProvider()
                              .Build();
            var result = await razorEngine.CompileRenderAsync("OrginalPost.cshtml", model);

            return(result);
        }