예제 #1
0
    private async Task <string> GetMJML(List <EntryModel> memories, string userId, string babyName)
    {
        var importResultModel = new ImportResultModel
        {
            Entries = memories
        };

        var model = DiaryService.GetDays(importResultModel);

        model.BabyName           = babyName;
        model.MemoriesBadgeCount = memories.Count;
        model.ShowMemoriesLink   = true;
        model.BaseUrl            = _configuration["BASE_URL"];
        model.Profile            = new Profile
        {
            UserId = userId
        };

        model.Entries = model.Entries
                        .OrderByDescending(entry => entry.TimeUTC.Year)
                        .OrderBy(entry => entry.TimeUTC.TimeOfDay);

        var mjml = await RazorTemplateEngine.RenderAsync("/Views/Emails/MemoriesEmail.cshtml", model);

        return(mjml);
    }
예제 #2
0
        /// <summary>
        /// Add /Home/ViewComponent to the URL to view this page
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> ViewComponent()
        {
            //Render View From the Web Application with View Component
            var renderedString = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewWithViewComponent.cshtml");

            return(Ok(renderedString));
        }
예제 #3
0
        public async Task SendNewTeamMemberNotice(Team team, User user, TeamRole role)
        {
            var viewbag = GetViewData();

            viewbag["Team"] = team;

            var model = new NewTeamMemberViewModel()
            {
                Team = team,
                User = user,
                Role = role
            };

            // add model data to email
            var prehtml = await RazorTemplateEngine.RenderAsync("/Views/NewTeamMember.cshtml", model, viewbag);

            // convert email to real html
            MjmlResponse mjml = await _mjmlServices.Render(prehtml);

            // build email
            using (var message = new MailMessage {
                From = _fromAddress, Subject = "UC Davis Payments Invitation"
            })
            {
                message.Body       = mjml.Html;
                message.IsBodyHtml = true;
                message.To.Add(new MailAddress(user.Email, user.Name));

                // ship it
                await _client.SendMailAsync(message);

                Log.Information("Sent Email");
            }
        }
예제 #4
0
        public async Task <Result <byte[]> > GeneratePdfAsync <T>(string filename, string templateId, T data,
                                                                  CancellationToken token)
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode     = ColorMode.Color,
                Orientation   = Orientation.Portrait,
                PaperSize     = PaperKind.A4,
                DocumentTitle = filename
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = await RazorTemplateEngine.RenderAsync($"~/Templates/{templateId}.cshtml", data),
                WebSettings =
                {
                    DefaultEncoding = "utf-8"
                },
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var result = _converter.Convert(pdf);

            return(Success(result));
        }
예제 #5
0
        public async Task <IActionResult> Get()
        {
            var html = await RazorTemplateEngine.RenderAsync("~/Views/PdfTemplate.cshtml");

            var rs = new LocalReporting()
                     .KillRunningJsReportProcesses()
                     .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? JsReportBinary.GetBinary() : jsreport.Binary.Linux.JsReportBinary.GetBinary())
                     .Configure(cfg => cfg.AllowedLocalFilesAccess().FileSystemStore().BaseUrlAsWorkingDirectory())
                     .AsUtility()
                     .Create();

            var generatedPdf = await rs.RenderAsync(new RenderRequest
            {
                Template = new Template
                {
                    Recipe  = Recipe.ChromePdf,
                    Engine  = Engine.None,
                    Content = html,
                    Chrome  = new Chrome
                    {
                        MarginTop    = "10",
                        MarginBottom = "10",
                        MarginLeft   = "50",
                        MarginRight  = "50"
                    }
                }
            });

            return(File(generatedPdf.Content, generatedPdf.Meta.ContentType, "GeneratedPdfFile.pdf"));
        }
        public async Task <string> HandleAsync(string modelJson)
        {
            var model = JsonConvert.DeserializeObject <ExampleSingleTemplateModel>(modelJson);
            var html  = await RazorTemplateEngine.RenderAsync(ViewPath, model);

            return(html);
        }
        /// <summary>
        /// Add /Home/Inject to the URL to view this  page
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> Inject()
        {
            //Render View From the Web Application with Injected Service
            var renderedString = await RazorTemplateEngine.RenderAsync("~/Views/Home/Inject.cshtml");

            return(Ok(renderedString));
        }
예제 #8
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                System.Console.WriteLine(DateTime.Now);
                var model = new ExampleModel()
                {
                    PlainText   = "Some text",
                    HtmlContent = "<em>Some emphasized text</em>"
                };

                var viewData = new Dictionary <string, object>();
                viewData["Value1"] = "1";
                viewData["Value2"] = "2";

                var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

                System.Console.Write(html);
                System.Console.WriteLine(DateTime.Now);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("{0}", e);
            }
        }
예제 #9
0
        private static async Task MainAsync()
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile($"appsettings.json", false)
                                    .Build();

            var feedUrl  = config["feed"];
            var location = config["location"];

            List <Video> videos = new List <Video>();

            var feed = await FeedReader.ReadAsync(feedUrl);

            var rss20feed = (CodeHollow.FeedReader.Feeds.AtomFeed)feed.SpecificFeed;

            foreach (var item in rss20feed.Items)
            {
                videos.Add(VideoMapper.XElementToVideo(item.Element));
            }

            var html = await RazorTemplateEngine.RenderAsync("~/Razor/index.cshtml", new IndexModel
            {
                Videos = videos,
            });

            await System.IO.File.WriteAllTextAsync($"{location}/Index.html", html);
        }
        public async Task <IActionResult> Template()
        {
            //Render View From the Template Library Application
            var renderedString = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewWithLayout.cshtml");

            return(Ok(renderedString));
        }
        public async Task RenderView_WithModelAndViewData_WithPartialView()
        {
            //Optionally call this to create cache of the renderer
            //Otherwise, render time will be more than usual on first time only
            RazorTemplateEngine.Initialize();
            // Arrange
            var model = new ExampleModel()
            {
                PlainText   = "Lorem Ipsium",
                HtmlContent = "<em>Lorem Ipsium</em>"
            };

            var viewData = new Dictionary <string, object>();

            viewData["Value1"] = "1";
            viewData["Value2"] = "2";

            // Act
            var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("Lorem Ipsium"));
            Assert.IsTrue(html.Contains("<em>Lorem Ipsium</em>"));
        }
예제 #12
0
        static async Task Main(string[] args)
        {
            try
            {
                System.Console.WriteLine(DateTime.Now);
                var model = new ExampleModel()
                {
                    PlainText   = "Some text",
                    HtmlContent = "<em>Some emphasized text</em>"
                };

                var viewData = new Dictionary <string, object>();
                viewData["Value1"] = "1";
                viewData["Value2"] = "2";

                var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

                System.Console.Write(html);
                System.Console.WriteLine(DateTime.Now);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("{0}", e);
            }

            System.Console.ReadLine();
        }
예제 #13
0
        public async Task <Result> SendTemplatedEmailAsync <T>(string toEmail, string toName, string subject,
                                                               string templateId, T data, IEnumerable <EmailAttachmentDto> attachments, bool isHtml,
                                                               CancellationToken token)
        {
            var msg = new SendRawEmailRequest
            {
                Source       = $"{_mailerOptions.Sender.Name}<{_mailerOptions.Sender.Email}>",
                Destinations = new List <string> {
                    $"=?UTF-8?B?{toName.Base64Encode()}?= <{toEmail}>"
                }
            };

            using (var messageStream = new MemoryStream())
            {
                var message = new MimeMessage();

                var content = await RazorTemplateEngine.RenderAsync($"~/Templates/{templateId}.cshtml", data);

                var builder = isHtml ? new BodyBuilder {
                    HtmlBody = content
                } : new BodyBuilder {
                    TextBody = content
                };

                message.To.Add(new MailboxAddress(toName, toEmail));
                message.From.Add(new MailboxAddress(_mailerOptions.Sender.Name, _mailerOptions.Sender.Email));
                message.Subject = subject;

                foreach (var attachment in attachments)
                {
                    builder.Attachments.Add(attachment.Name, attachment.Content);
                }

                message.Body = builder.ToMessageBody();
                await message.WriteToAsync(messageStream, token);

                msg.RawMessage = new RawMessage()
                {
                    Data = messageStream
                };
            }

            if (_mailerOptions.SkipSending)
            {
                return(Success());
            }

            var response = await _mailer.SendRawEmailAsync(msg, token);

            if ((int)response.HttpStatusCode >= 400)
            {
                return(Failure("Une erreur est survenue pendant l'envoi de l'email avec pièce jointe.",
                               response.ResponseMetadata.Metadata));
            }

            return(Success());
        }
        public async Task RenderView_WithLayout_WithoutData()
        {
            // Act
            var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewWithLayout.cshtml");

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("This is the view content"));
        }
        public async Task RenderView_WithViewComponent()
        {
            // Act
            var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewWithViewComponent.cshtml");

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains(@"Example View Component!"));
        }
        public async Task RenderView_WithTagHelpers()
        {
            // Act
            var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewWithTagHelpers.cshtml");

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains(@"<label class=""caption"" for=""FirstName"">First Name:</label>"));
            Assert.IsTrue(html.Contains(@"<a href="""">All Speakers</a>"));
        }
예제 #17
0
        static async Task Main(string[] args)
        {
            var invoiceModel = new Templates.Invoice
            {
                InvoiceNumber  = "3232",
                CreatedDate    = DateTime.Now,
                DueDate        = DateTime.Now.AddDays(7),
                CompanyAddress = new Templates.Address
                {
                    Name         = "XY Technologies",
                    AddressLine1 = "XY Street, Park Road",
                    City         = "Chennai",
                    Country      = "India",
                    Email        = "*****@*****.**",
                    PinCode      = "600001"
                },
                BillingAddress = new Templates.Address
                {
                    Name         = "XY Customer",
                    AddressLine1 = "ZY Street, Loyal Road",
                    City         = "Bangalore",
                    Country      = "India",
                    Email        = "*****@*****.**",
                    PinCode      = "343099"
                },
                PaymentMethod = new Templates.PaymentMethod
                {
                    Name            = "Cheque",
                    ReferenceNumber = "94759849374"
                },
                LineItems = new List <Templates.LineItem>
                {
                    new Templates.LineItem
                    {
                        Id           = 1,
                        ItemName     = "USB Type-C Cable",
                        Quantity     = 3,
                        PricePerItem = 10.33M
                    },
                    new Templates.LineItem
                    {
                        Id           = 1,
                        ItemName     = "SSD-512G",
                        Quantity     = 10,
                        PricePerItem = 90.54M
                    }
                },
                CompanyLogoUrl = "https://raw.githubusercontent.com/soundaranbu/RazorTemplating/master/src/Razor.Templating.Core/assets/icon.png"
            };
            var invoiceHtml = await RazorTemplateEngine.RenderAsync("~/Invoice.cshtml", invoiceModel);

            Console.WriteLine(invoiceHtml);
            Console.ReadLine();
        }
예제 #18
0
        public async Task Register(string email, string baseUrl)
        {
            var confirmAccountModel = new ConfirmAccountEmailViewModel($"{baseUrl}/{Guid.NewGuid()}");

            string body = await RazorTemplateEngine.RenderAsync("/Views/Emails/ConfirmAccount/ConfirmAccountEmail.cshtml", confirmAccountModel);

            var toAddresses = new List <string> {
                email
            };

            SendEmail(toAddresses, "*****@*****.**", "Confirm your Account", body);
        }
 public async Task RenderInvalidView_Should_ThrowError()
 {
     try
     {
         var html = await RazorTemplateEngine.RenderAsync("/Views/SomeInvalidView.cshtml");
     }
     catch (System.Exception e)
     {
         Assert.IsTrue(e is InvalidOperationException);
         Assert.IsTrue(e.Message.Contains("Unable to find view '/Views/SomeInvalidView.cshtml'."));
     }
 }
예제 #20
0
        public async Task <Result> SendTemplatedEmailAsync <T>(string toEmail, string toName, string subject,
                                                               string templateId, T data, bool isHtml, CancellationToken token)
        {
            var msg = new SendEmailRequest();

            msg.Destination = new Destination
            {
                ToAddresses = new List <string> {
                    $"=?UTF-8?B?{toName.Base64Encode()}?= <{toEmail}>"
                }
            };

            msg.Source     = $"{_mailerOptions.Sender.Name}<{_mailerOptions.Sender.Email}>";
            msg.ReturnPath = _mailerOptions.Bounces;
            msg.Message    = new Message
            {
                Subject = new Content(subject)
            };

            var content = await RazorTemplateEngine.RenderAsync($"~/Templates/{templateId}.cshtml", data);

            if (isHtml)
            {
                msg.Message.Body = new Body {
                    Html = new Content(content)
                }
            }
            ;
            else
            {
                msg.Message.Body = new Body {
                    Text = new Content(content)
                }
            };

            if (_mailerOptions.SkipSending)
            {
                return(Success());
            }

            var response = await _mailer.SendEmailAsync(msg, token);

            if ((int)response.HttpStatusCode >= 400)
            {
                return(Failure("Une erreur est survenue pendant l'envoi de l'email.",
                               response.ResponseMetadata.Metadata));
            }

            return(Success());
        }
예제 #21
0
        public async Task SendInvoice(Invoice invoice, string ccEmails, string bccEmails)
        {
            var viewbag = GetViewData();

            viewbag["Team"] = invoice.Team;

            var model = new InvoiceViewModel
            {
                Invoice = invoice,
            };

            // add model data to email
            var prehtml = await RazorTemplateEngine.RenderAsync("/Views/Invoice.cshtml", model, viewbag);

            // convert email to real html
            MjmlResponse mjml = await _mjmlServices.Render(prehtml);

            // build email
            using (var message = new MailMessage {
                From = _fromAddress, Subject = $"New invoice from {invoice.Team.Name}"
            })
            {
                message.Body       = mjml.Html;
                message.IsBodyHtml = true;
                message.To.Add(new MailAddress(invoice.CustomerEmail, invoice.CustomerName));

                // add cc
                if (!string.IsNullOrWhiteSpace(ccEmails))
                {
                    ccEmails.Split(';', StringSplitOptions.RemoveEmptyEntries)
                    .Select(e => new MailAddress(e))
                    .ToList()
                    .ForEach(e => message.CC.Add(e));
                }

                // add bcc
                if (!string.IsNullOrWhiteSpace(bccEmails))
                {
                    bccEmails.Split(';', StringSplitOptions.RemoveEmptyEntries)
                    .Select(e => new MailAddress(e))
                    .ToList()
                    .ForEach(e => message.Bcc.Add(e));
                }

                // ship it
                await _client.SendMailAsync(message);

                Log.Information("Sent Email");
            }
        }
        public async Task RenderView_WithLayout_WithViewData()
        {
            // Arrange
            var viewData = new Dictionary <string, object>();

            viewData["Title"] = "This is Title";

            // Act
            var html = await RazorTemplateEngine.RenderAsync <object>("~/Views/ExampleViewWithLayout.cshtml", null, viewData);

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("This is the view content"));
            Assert.IsTrue(html.Contains("This is Title"));
        }
        public async Task RenderView_WithModel_WithViewImport()
        {
            // Arrange
            var model = new ExampleModel()
            {
                PlainText   = "Lorem Ipsium",
                HtmlContent = "<em>Lorem Ipsium</em>"
            };

            // Act
            var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewUsingViewImports.cshtml", model);

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("Plain text: Lorem Ipsium"));
        }
        public async Task RenderParitialView_WithModel()
        {
            // Arrange
            var model = new ExampleModel()
            {
                PlainText   = "Lorem Ipsium",
                HtmlContent = "<em>Lorem Ipsium</em>"
            };

            // Act
            var html = await RazorTemplateEngine.RenderAsync("~/Views/ExamplePartialView.cshtml", model);

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("Partial view"));
            Assert.IsTrue(html.Contains("Html content: <em>Lorem Ipsium</em>"));
        }
예제 #25
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var model = new ExampleModel()
            {
                PlainText   = "Some text",
                HtmlContent = "<em>Some emphasized text</em>"
            };

            var viewData = new Dictionary <string, object>();

            viewData["Value1"] = "1";
            viewData["Value2"] = "2";

            var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

            return(new OkObjectResult(html));
        }
예제 #26
0
        public async Task RenderView_WithModelAndViewData()
        {
            // Act
            var model = new ExampleModel()
            {
                PlainText   = "Lorem Ipsium",
                HtmlContent = "<em>Lorem Ipsium</em>"
            };

            var viewData = new Dictionary <string, object>();

            viewData["Value1"] = "1";
            viewData["Value2"] = "2";

            var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

            // Assert
            Assert.IsNotNull(html);
            Assert.IsTrue(html.Contains("Lorem Ipsium"));
            Assert.IsTrue(html.Contains("<em>Lorem Ipsium</em>"));
        }
예제 #27
0
        // GET: Orders/DownloadInvoice
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        // Action -> print or donwload
        public async Task <IActionResult> DownloadInvoice(string invoiceAction)
        {
            Cart cart = await _helper.GetFullCartData(SessionNames.INVOICE);

            ViewBag.Action = invoiceAction;

            if (invoiceAction == "print")
            {
                return(View("InvoiceToPrint", cart));
            }

            string body = await RazorTemplateEngine.RenderAsync(@"~/Views/Orders/InvoiceToPrint.cshtml", cart);


            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10, Bottom = 10
                },
                DocumentTitle = "Invoice"
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = body,
                FooterSettings = { FontName = "Arial", FontSize = 10, Left = "DMS-OShopping", Line = true, Right = "Page [page] of [toPage]" }
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Invoice.pdf"));
        }
예제 #28
0
        public async Task SendReceipt(Invoice invoice, PaymentEvent payment)
        {
            var viewbag = GetViewData();

            viewbag["Team"] = invoice.Team;

            var model = new ReceiptViewModel
            {
                Invoice = invoice,
                Payment = payment,
            };

            // add model data to email
            var prehtml = await RazorTemplateEngine.RenderAsync("/Views/Receipt.cshtml", model, viewbag);

            // convert email to real html
            var mjml = await _mjmlServices.Render(prehtml);

            // build email
            using (var message = new MailMessage {
                From = _fromAddress, Subject = $"Receipt from {invoice.Team.Name}"
            })
            {
                message.Body       = mjml.Html;
                message.IsBodyHtml = true;
                message.To.Add(new MailAddress(invoice.CustomerEmail, invoice.CustomerName));

                // add cc if the billing email is different
                if (!string.Equals(invoice.CustomerEmail, payment.BillingEmail, StringComparison.OrdinalIgnoreCase))
                {
                    var ccName = $"{payment.BillingFirstName} {payment.BillingLastName}";
                    message.CC.Add(new MailAddress(payment.BillingEmail, ccName));
                }

                // ship it
                await _client.SendMailAsync(message);

                Log.Information("Sent Email");
            }
        }
예제 #29
0
        private async void renderButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var model = new ExampleModel()
                {
                    PlainText   = "This text is rendered from Razor View using Razor.Templating.Core Library",
                    HtmlContent = "<em>You can do awesome stuff like Reporting, Invoicing, etc,. Try it today</em>"
                };

                var viewData = new Dictionary <string, object>();
                viewData["Value1"] = "1";
                viewData["Value2"] = "2";

                var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewData);

                textBlock.Text = html;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }
예제 #30
0
        public async Task SendRefundRequest(Invoice invoice, PaymentEvent payment, string refundReason, User user)
        {
            var viewbag = GetViewData();

            viewbag["Team"] = invoice.Team;
            viewbag["Slug"] = invoice.Team.Slug;

            var model = new RefundRequestViewModel()
            {
                Invoice      = invoice,
                Payment      = payment,
                RefundReason = refundReason,
                User         = user,
            };

            // add model data to email
            var prehtml = await RazorTemplateEngine.RenderAsync("/Views/RefundRequest.cshtml", model, viewbag);

            // convert email to real html
            MjmlResponse mjml = await _mjmlServices.Render(prehtml);

            // build email
            using (var message = new MailMessage {
                From = _fromAddress, Subject = $"Refund Request from {invoice.Team.Name}"
            })
            {
                message.Body       = mjml.Html;
                message.IsBodyHtml = true;
                message.To.Add(_refundAddress);

                // ship it
                await _client.SendMailAsync(message);

                Log.Information("Sent Email");
            }
        }