Пример #1
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.FindByEmailAsync(model.UserName);

            if (user == null)
            {
                ModelState.AddModelError("", "Utilisateur introuvable");
                return(View(model));
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var url = Url.Action("ResetPassword", "Account", new { userId = user.Id, token = token, returnUrl = model.ReturnUrl }, Url.ActionContext.HttpContext.Request.Scheme);

            var msg = new SendEmailRequest();

            msg.Destination = new Destination
            {
                ToAddresses = new List <string> {
                    $"{user.FirstName}<{user.Email}>"
                }
            };

            msg.Source     = $"{_configuration.GetValue<string>("mailer:sender:name")}<{_configuration.GetValue<string>("mailer:sender:email")}>";
            msg.ReturnPath = _configuration.GetValue <string>("mailer:bounces");
            msg.Message    = new Message
            {
                Subject = new Content("Réinitialisation de votre mot de passe")
            };

            var content = await _templateEngine.CompileRenderAsync("ResetPasswordEvent.cshtml", new { UserName = $"{user.FirstName} {user.LastName}", Url = url });

            msg.Message.Body = new Body {
                Html = new Content(content)
            };

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

            if ((int)response.HttpStatusCode >= 400)
            {
                ModelState.AddModelError("", "Une erreur est survenue lors de l'envoi de l'email de réinitialisation.");
                return(View(model));
            }

            model.Sent = true;
            return(View(model));
        }
Пример #2
0
        public async Task <byte[]> Create()
        {
            try
            {
                var model = new List <CarModel>()
                {
                    new CarModel {
                        NameOfCar = "Audi Q7", FirstRegistration = DateTime.UtcNow.AddYears(-3), MaxSpeed = 200, NumberOfDoors = 4
                    },
                    new CarModel {
                        NameOfCar = "Audi A5", FirstRegistration = DateTime.UtcNow, MaxSpeed = 180, NumberOfDoors = 4
                    },
                    new CarModel {
                        NameOfCar = "Audi Q3", FirstRegistration = DateTime.UtcNow, MaxSpeed = 245, NumberOfDoors = 2
                    },
                    new CarModel {
                        NameOfCar = "Mercedes SLI", FirstRegistration = DateTime.UtcNow, MaxSpeed = 150, NumberOfDoors = 4
                    },
                    new CarModel {
                        NameOfCar = "Chevrolet", FirstRegistration = DateTime.UtcNow, MaxSpeed = 220, NumberOfDoors = 4
                    },
                    new CarModel {
                        NameOfCar = "BMW", FirstRegistration = DateTime.UtcNow, MaxSpeed = 200, NumberOfDoors = 4
                    },
                };
                var    templatePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), $"PdfTemplates/CarPdf.cshtml");
                string template     = await _razorEngine.CompileRenderAsync(templatePath, model);

                var globalSettings = new GlobalSettings
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Margins     = new MarginSettings()
                    {
                        Top = 10, Bottom = 10, Left = 10, Right = 10
                    },
                    DocumentTitle = "Simple PDF document",
                };
                var objectSettings = new ObjectSettings
                {
                    PagesCount     = true,
                    HtmlContent    = template,
                    WebSettings    = { DefaultEncoding = "utf-8" },
                    HeaderSettings = { FontName = "Arial", FontSize = 12, Line = true, Center = "Fun pdf document" },
                    FooterSettings = { FontName = "Arial", FontSize = 12, Line = true, Right = "Page [page] of [toPage]" }
                };
                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };
                byte[] file = _pdfConverter.Convert(pdf);
                return(file);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task <string> RenderTemplateAsync <TViewModel>(string filePath, TViewModel viewModel)
        {
            var template = File.ReadAllText(Path.Combine("Templates", filePath));
            var name     = Path.GetFileNameWithoutExtension(filePath);

            return(await _engine.CompileRenderAsync(name, template, viewModel));
        }
Пример #4
0
        public async Task <String> Render(BuildContext context)
        {
            _logger.LogDebug($"------ Render Build:{context.BuildKey} Start! ------");
            context.Result = await _razorLightEngine.CompileRenderAsync <BuildContext>(context.Build.Template, context);

            _logger.LogDebug($"------ Render Build:{context.BuildKey} End! ------");
            return(context.Result);
        }
Пример #5
0
        public async Task <HttpResponseMessage> GetDetail(string code, string instanceId, HttpRequestMessage request, string errorMessage = null)
        {
            var table = _tableClient.GetTableReference($"{_taskHubName}History");

            if (!await table.ExistsAsync())
            {
                return(request.CreateResponse(HttpStatusCode.NotFound));
            }

            var entities = (await table.GetByPartition <HistoryTableEntity>(instanceId))
                           .OrderBy(x => x.RowKey)
                           .Select(x => new HistoryItemViewModel
            {
                Detail                = x.Detail,
                EventId               = x.EventId,
                EventType             = x.EventType,
                TimeStamp             = x.Timestamp.ToOffset(TimeSpan.FromHours(_confg.OffsetHour)),
                ExecutionId           = x.ExecutionId,
                Input                 = x.Input,
                IsPlayed              = x.IsPlayed,
                Name                  = x.Name,
                OrchestrationInstance = x.OrchestrationInstance,
                OrchestrationStatus   = x.OrchestrationStatus,
                Reason                = x.Reason,
                Result                = x.Result,
                TaskScheduledId       = x.TaskScheduledId,
                Row = x.RowKey
            })
                           .ToList();
            var vm = new HistoryViewModel
            {
                Code         = code,
                List         = entities,
                InstanceId   = instanceId,
                ErrorMessage = errorMessage
            };
            var html = await _razorLightEngine.CompileRenderAsync(
                "Views.Detail.cshtml", vm);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(html, Encoding.UTF8, "text/html")
            });
        }
Пример #6
0
        private MailMessage GetMessage(OrderViewModel model)
        {
            var message = new MailMessage();

            message.From = new MailAddress(_settings.FromAddress);
            message.To.Add(_settings.DeliveryAddresses);
            message.Subject    = "TEST"; //can be also templated as a body
            message.Body       = _renderEngine.CompileRenderAsync("OrderCreatedView.cshtml", model).Result;
            message.IsBodyHtml = true;
            return(message);
        }
Пример #7
0
        /// <inheritdoc />
        public async Task <string> RenderAsync <T>(string template, T model)
        {
            if (!template.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase))
            {
                template += ".cshtml";
            }

            var result = await _engine.CompileRenderAsync(template, model);

            return(result);
        }
Пример #8
0
        /// <summary>
        /// Get the Compiled Configuration Template.
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetStringConfig()
        {
            // Check if the engine exists.
            if (_engine == null)
            {
                // The engine does not exist, throw an exception.
                throw RazorLightEngineMissingException();
            }

            // Return the rendered template.
            return(await _engine.CompileRenderAsync("OpenVPN", this));
        }
        public async Task <bool> Initialize()
        {
            engine = new RazorLightEngineBuilder()
                     .UseMemoryCachingProvider()
                     .Build();

            await engine.CompileRenderAsync <DataTable>(key, Content, new DataTable());

            var found = engine.TemplateCache.RetrieveTemplate(key);

            return(found.Success);
            //return true;
        }
Пример #10
0
        public async Task <string> RenderTemplateAsync <TViewModel>(string filePath, TViewModel viewModel)
        {
            var template = await FileEx.ReadAllTextAsync(Path.Combine("Templates", filePath));

            var name = Path.Combine("Templates", filePath)
                       .Replace('.', '_')
                       .Replace(Path.PathSeparator, '_')
                       .Replace(Path.VolumeSeparatorChar, '_')
                       .Replace(Path.AltDirectorySeparatorChar, '_')
                       .Replace(Path.DirectorySeparatorChar, '_');

            return(await _engine.CompileRenderAsync(name, template, viewModel));
        }
Пример #11
0
        public async Task <IEnumerable <WeatherForecast> > Get()
        {
            var result = await _razorLightEngine.CompileRenderAsync("Areas.MyFeature.Pages.Page1", new Page1Model());

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
Пример #12
0
        public async Task <Stream> ExportAsync(DtoResume resume)
        {
            var dict = _modelBuilder.Build(resume);

            var result = await _engine.CompileRenderAsync(_viewPath, dict);

            var report = await _reportMVCService.RenderAsync(new RenderRequest()
            {
                Template = new Template
                {
                    Content = result,
                    Engine  = Engine.None,
                    Recipe  = Recipe.ChromePdf
                }
            });

            return(report.Content);
        }
Пример #13
0
        public async void SendEmailAsync(string email, string subject, string emailTemplateFileName, object model)
        {
            string resultFromFile;

            try
            {
                resultFromFile = await _engine.CompileRenderAsync(emailTemplateFileName, model);
            }
            catch (Exception ex)
            {
                _logger.LogInformation($"The email template does not exist, {ex}");
                return;
            }

            var exchange = new ExchangeService();
            var userName = Environment.GetEnvironmentVariable("EMAIL_USERNAME");
            var password = Environment.GetEnvironmentVariable("EMAIL_PASSWORD");
            var domain   = Environment.GetEnvironmentVariable("EMAIL_DOMAIN");

            exchange.Credentials = new WebCredentials(userName, password, domain);
            exchange.Url         = new Uri("https://email.bhhsall.com/EWS/Exchange.asmx");

            EmailMessage msg = new EmailMessage(exchange)
            {
                Subject = subject,
                Body    = resultFromFile
            };

            msg.ToRecipients.Add(email);

            try
            {
                await msg.SendAndSaveCopy();

                _logger.LogInformation("Message sent successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
            }
        }
        public EmailRequest GenerateEmail(object model)
        {
            if (!(model is ContactUsModel contactUsModel))
            {
                throw new ArgumentException($"{nameof(model)} must be of type {nameof(ContactUsModel)}", nameof(model));
            }

            var template = _razorLightEngine.CompileRenderAsync(EmailTemplateName, contactUsModel).Result;

            return(new EmailRequest
            {
                To = _emailMessageSettings.To,
                From = contactUsModel.EmailAddress,
                Cc = _emailMessageSettings.Cc,
                Bcc = _emailMessageSettings.Bcc,
                ReplyTo = _emailMessageSettings.ReplyTo,
                Subject = "Practice Transitions : Contact Us",
                Body = template,
                IsBodyHtml = true
            });
        }
Пример #15
0
        public async Task <byte[]> Create(IEnumerable <CampaignDTO> verification)
        {
            var    model        = verification;
            var    templatePath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).FullName, $"Api/Infrastructure/Template.cshtml");
            string template     = await _razorEngine.CompileRenderAsync(templatePath, model);


            var globalSetting = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "Raport"
                                //Out = @"D:\raport.PDF"
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = template,
                WebSettings    = { DefaultEncoding = "utf-8" },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };

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


            byte[] file = _pdfConverter.Convert(pdf);
            return(file);
        }
        public EmailRequest GenerateEmail(object model)
        {
            if (!(model is CreateModel createModel))
            {
                throw new ArgumentException(nameof(model));
            }

            var template =
                _razorLightEngine.CompileRenderAsync(EmailTemplateName, model).Result;

            return(new EmailRequest
            {
                To = _emailMessageSettings.To,
                From = _emailMessageSettings.From,
                Cc = _emailMessageSettings.Cc,
                Bcc = _emailMessageSettings.Bcc,
                ReplyTo = _emailMessageSettings.ReplyTo,
                Subject = "Practice Transitions : Job Post",
                Body = template,
                IsBodyHtml = true,
                Attachments = GenerateEmailAttachments(createModel)
            });
        }
Пример #17
0
        public async Task <byte[]> Create()
        {
            var    model        = Data.CarRepository.GetCars();
            var    templatePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), $"Templates/PDFTemplate.cshtml");
            string template     = await _razorEngine.CompileRenderAsync(templatePath, model);

            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings()
                {
                    Top = 10, Bottom = 10, Left = 10, Right = 10
                },
                DocumentTitle = "Simple PDF document",
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = template,
                WebSettings    = { DefaultEncoding = "utf-8" },
                HeaderSettings = { FontName = "Arial", FontSize = 12, Line = true, Center = "Fun pdf document" },
                FooterSettings = { FontName = "Arial", FontSize = 12, Line = true, Right = "Page [page] of [toPage]" }
            };

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

            byte[] file = _pdfConverter.Convert(pdf);

            return(file);
        }
Пример #18
0
 public Task <string> TransformAsync(string viewName, object model)
 {
     return(_engine.CompileRenderAsync(viewName + ".cshtml", model));
 }
Пример #19
0
 /// <summary>	Parses. </summary>
 /// <typeparam name="TModel">	Type of the model. </typeparam>
 /// <param name="viewName">	Name of the view. </param>
 /// <param name="model">    The model. </param>
 /// <returns>	A string. </returns>
 public override string Parse <TModel>(string viewName, TModel model)
 {
     Logger?.LogInformation($"Parsing view '{viewName}' for model '{typeof(TModel).Name}'.");
     return(Engine.CompileRenderAsync(viewName, model).Result);
 }
 public Task <string> GenerateAsync(string template, object model)
 {
     return(_razorLightEngine.CompileRenderAsync(template, model));
 }
Пример #21
0
        public async Task <int> SendBookingConfirmEmail(BookingEmailViewModel emailViewModel, string hostEmail, string hostName)
        {
            //var engine = EngineFactory.CreatePhysical(_appSettings.EmailTemplateFolder);
            //var engine = EngineFactory.CreatePhysical($"{Directory.GetCurrentDirectory()}\\Content\\EmailTemplates");

            emailViewModel.EmailHeader = $"Hi, thanks for your booking";
            var emailContentForGuests = await _razorLightEngine.CompileRenderAsync(_appSettings.BookingGuestsEmailTemplate, emailViewModel);

            emailViewModel.EmailHeader = $"Hi, you have a new booking";
            emailViewModel.IsHost      = true;
            var emailContentForHost = await _razorLightEngine.CompileRenderAsync(_appSettings.BookingGuestsEmailTemplate, emailViewModel);

            var emailLogs = new List <EmailLog>();

            var particiants = string.Join(",", emailViewModel.BookingParticipants.Select(x => x.Email));

            if (_appSettings.Environment != "prod")
            {
                particiants = "*****@*****.**";

                emailLogs.Add(new EmailLog
                {
                    ListingId   = emailViewModel.ListingId,
                    FromAddress = _appSettings.DefaultEmailAddress,
                    ToAddress   = string.Join(",", particiants),
                    Subject     = _appSettings.BookingEmailSubject,
                    Content     = emailContentForGuests,
                    CreatedDate = DateTime.Now,
                    //MessageId = x.Result.MessageID,
                    //TransactionId = x.Result.TransactionID,
                    Status = true
                });

                emailLogs.Add(new EmailLog
                {
                    ListingId   = emailViewModel.ListingId,
                    FromAddress = _appSettings.DefaultEmailAddress,
                    ToAddress   = hostEmail,
                    Subject     = _appSettings.BookingEmailSubject,
                    Content     = emailContentForHost,
                    CreatedDate = DateTime.Now,
                    //MessageId = x.Result.MessageID,
                    //TransactionId = x.Result.TransactionID,
                    Status = true
                });
            }
            else
            {
                var sendList = new List <Task>
                {
                    ElasticEmailClient.Send(_appSettings.BookingEmailSubject, _appSettings.DefaultEmailAddress, _appSettings.DefaultEmailName, to: particiants, bodyHtml: emailContentForGuests, isTransactional: true)
                    .ContinueWith(x => emailLogs.Add(new EmailLog
                    {
                        ListingId     = emailViewModel.ListingId,
                        FromAddress   = _appSettings.DefaultEmailAddress,
                        ToAddress     = string.Join(",", particiants),
                        Subject       = _appSettings.BookingEmailSubject,
                        Content       = emailContentForGuests,
                        CreatedDate   = DateTime.Now,
                        MessageId     = x.Result.MessageID,
                        TransactionId = x.Result.TransactionID,
                        Status        = true
                    })),
                    ElasticEmailClient.Send(_appSettings.BookingEmailSubject, _appSettings.DefaultEmailAddress, _appSettings.DefaultEmailName, to: hostEmail, bodyHtml: emailContentForHost, isTransactional: true)
                    .ContinueWith(x => emailLogs.Add(new EmailLog
                    {
                        ListingId     = emailViewModel.ListingId,
                        FromAddress   = _appSettings.DefaultEmailAddress,
                        ToAddress     = hostEmail,
                        Subject       = _appSettings.BookingEmailSubject,
                        Content       = emailContentForHost,
                        CreatedDate   = DateTime.Now,
                        MessageId     = x.Result.MessageID,
                        TransactionId = x.Result.TransactionID,
                        Status        = true
                    }))
                };

                await Task.WhenAll(sendList);
            }

            return(await _emailLogRepository.LogEmail(emailLogs));

            //return sendList.Select(x => x.Result).ToList();
        }
Пример #22
0
 private async Task <string> CreateResetMail(PasswordResetViewModel viewModel)
 {
     return(await razorLightEngine.CompileRenderAsync("Mail/ResetMail.cshtml", viewModel));
 }
Пример #23
0
        public async Task <string> ParseAsync <T>(string template, T model, bool isHtml = true)
        {
            dynamic viewBag = (model as IViewBagModel)?.ViewBag;

            return(await _engine.CompileRenderAsync <T>(GetHashString(template), template, model, viewBag));
        }
Пример #24
0
 public async Task VerifyCrowdactionAddedAdmin()
 => await Verifier.Verify(await engine.CompileRenderAsync("CrowdactionAddedAdmin.cshtml", "test"));
 /// <summary>	Parses. </summary>
 /// <typeparam name="TModel">	Type of the model. </typeparam>
 /// <param name="viewName">	Name of the view. </param>
 /// <param name="model">    The model. </param>
 /// <returns>	A string. </returns>
 public override string Parse <TModel>(string viewName, TModel model)
 {
     return(Engine.CompileRenderAsync(viewName, model).Result);
 }
Пример #26
0
        public async Task SendEmailsTemplated <TModel>(IEnumerable <string> emails, string subject, string emailTemplate, TModel model)
        {
            string message = await engine.CompileRenderAsync($"{emailTemplate}.cshtml", model).ConfigureAwait(false);

            SendEmails(emails, subject, message);
        }
Пример #27
0
        public override async Task <ReadOnlyMemory <byte> > GenerateAsync()
        {
            var renderedPage = await _razor.CompileRenderAsync(_templateName, _model);

            return(Encoding.UTF8.GetBytes(renderedPage));
        }
Пример #28
0
        public async Task <string> Generate <T>(T data)
        {
            var template = typeof(T).Name;

            return(await _razorLightEngine.CompileRenderAsync($"{template}/{template}.cshtml", data));
        }
Пример #29
0
        // TODO: Look into whether making this a responsibility of the service itself (generation) is a more sane appraoch
        // This would foster loose coupling
        private async Task <UserServiceResource> GenerateUserServiceResource(User user, Type type, IEnumerable <IServiceConfig> configs)
        {
            var serviceReference = new UserServiceResource();

            EnsureServiceAccess(user, type);

            // Giant hack, but hey, it works ┐(´∀`)┌ヤレヤレ
            switch (true)
            {
            case bool _ when type == typeof(HTTPProxy):
                // HTTPProxy has a global config, and thus only one instance
                // Guaranteed to not be null, so inspection is not needed.
                // ReSharper disable once AssignNullToNotNullAttribute
                var config  = (HTTPConfig)configs.First();
                var proxies = new List <string>();
                foreach (var listener in config.listeners)
                {
                    // Gotta translate 0.0.0.0 into something people can actually connect to
                    // This is currently replaced by the default outgoing IP, which should work assuming NAT port forwarding succeeded
                    // Or there is no NAT involved.
                    proxies.Add(await _ipResolver.Translate(listener.Item1) + ":" + listener.Item2);
                }

                serviceReference.AccessReference   = proxies;
                serviceReference.AccessCredentials = Messages.SPECTERO_USERNAME_PASSWORD;
                break;

            case bool _ when type == typeof(OpenVPN):
                // OpenVPN is a multi-instance service
                var allListeners = new List <OpenVPNListener>();

                OpenVPNConfig sanitizedOpenVPNConfig = null;

                foreach (var vpnConfig in configs)
                {
                    var castConfig = vpnConfig as OpenVPNConfig;
                    if (castConfig?.Listener != null)
                    {
                        // ReSharper disable once InconsistentNaming
                        var translatedIP = await _ipResolver.Translate(castConfig.Listener.IPAddress);

                        // This is done to force a translation of local addresses
                        castConfig.Listener.IPAddress = translatedIP.ToString();

                        allListeners.Add(castConfig.Listener);

                        // Setting it only once would be ideal, but eh -- overhead is low enough to make this work.
                        sanitizedOpenVPNConfig = castConfig;
                    }
                }

                if (!allListeners.IsNullOrEmpty())
                {
                    serviceReference.AccessConfig = await _razorLightEngine.CompileRenderAsync("OpenVPNUser", new OpenVPNUserConfig
                    {
                        Listeners  = allListeners,
                        User       = user,
                        Identity   = _identityProvider.GetGuid().ToString(),
                        BaseConfig = sanitizedOpenVPNConfig
                    });

                    serviceReference.AccessCredentials = user.CertKey.IsNullOrEmpty()
                            ? Messages.SPECTERO_USERNAME_PASSWORD
                            : user.CertKey;
                }

                break;
            }

            return(serviceReference);
        }