Ejemplo n.º 1
0
        public async Task <IActionResult> Edit(string id, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageEmailTemplates))
            {
                return(Forbid());
            }

            var templatesDocument = await _templatesManager.GetEmailTemplatesDocumentAsync();

            if (!templatesDocument.Templates.ContainsKey(id))
            {
                return(RedirectToAction("Create", new { id, returnUrl }));
            }

            var template = templatesDocument.Templates[id];

            var model = new EmailTemplateViewModel
            {
                Id                   = id,
                Name                 = template.Name,
                Body                 = template.Body,
                Description          = template.Description,
                AuthorExpression     = template.AuthorExpression,
                SenderExpression     = template.SenderExpression,
                ReplyToExpression    = template.ReplyToExpression,
                RecipientsExpression = template.RecipientsExpression,
                CCExpression         = template.CCExpression,
                BCCExpression        = template.BCCExpression,
                SubjectExpression    = template.SubjectExpression,
                IsBodyHtml           = template.IsBodyHtml,
            };

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Ejemplo n.º 2
0
        public ActionResult MyWondersEmailTemplate(string id)
        {
            try
            {
                var user = DataContext.AspNetUsers.FirstOrDefault(u => u.Id == id);
                if (user != null)
                {
                    var amountToSkip  = user.MyWonders.Count <= NumberOfWonders ? 0 : user.MyWonders.Count - NumberOfWonders;
                    var recentWonders = user.MyWonders.Where(x => x.Archived != true).Skip(amountToSkip).Reverse();
                    //var recentWonders = user.MyWonders.Skip(user.MyWonders.Count - NumberOfWonders);


                    var model = new EmailTemplateViewModel();
                    model.User    = Mapper.Map <UserModel>(user);
                    model.Wonders = Mapper.Map <List <DealModel> >(recentWonders);

                    //TODO: move these to config properties
                    model.UrlString       = "https://cms.thewonderapp.co/content/images/";
                    model.UnsubscribeLink = "mailto:[email protected] ";

                    return(View(model));
                }
                return(View());
            }

            catch (Exception ex)
            {
                AddClientMessage(ClientMessage.Warning, ex.Message);
                return(View());
            }
        }
 public bool InsertTemplate(EmailTemplateViewModel model, string userid)
 {
     using (var connection = new SqlConnection(connectionString))
     {
         try
         {
             SqlParameter[] parameters = new SqlParameter[] {
                 new SqlParameter("@UserId", userid),
                 new SqlParameter("@Name", model.Name),
                 new SqlParameter("@Subject", model.Subject),
                 new SqlParameter("@UserRole", model.UserRole),
                 new SqlParameter("@EmailBody", model.EmailBody),
             };
             var data =
                 SqlHelper.ExecuteNonQuery
                 (
                     connection,
                     CommandType.StoredProcedure,
                     "usp_InsertEmailTemplate",
                     parameters
                 );
             if (data > 0)
             {
                 return(true);
             }
         }
         finally
         {
             SqlHelper.CloseConnection(connection);
         }
     }
     throw new Exception("Unable to delete data");
 }
        public IActionResult SendNotificationMail([FromBody] EmailTemplateViewModel model)
        {
            //IEnumerable<EmailTemplateViewModel> emailTemplate = null;

            string[] Emails = model.EmailId.Split(',').Select(sValue => sValue.Trim()).ToArray();

            string message = "fail";

            for (int i = 0; i < Emails.Length; i++)
            {
                try
                {
                    var eModel = new EmailViewModel
                    {
                        Subject  = model.Subject,
                        Body     = model.EmailBody,
                        To       = new string[] { Emails[i] },
                        From     = config["EmailCredential:Fromemail"],
                        IsHtml   = true,
                        MailType = (int)MailType.OTP
                    };
                    emailHandler.SendMail(eModel, -1);
                    message = "Pass";
                }
                catch (DataNotFound ex)
                {
                    Logger.Logger.WriteLog(Logger.Logtype.Error, ex.Message, 0, typeof(DashboardController), ex);
                    ModelState.AddModelError("ErrorMessage", string.Format("{0}", ex.Message));
                }
            }

            return(Json(message));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> EmailTemplateDetails(Guid ID, bool Success = false)
        {
            EmailTemplateViewModel model = new EmailTemplateViewModel();

            try
            {
                model._context         = _context;
                model._emailService    = _emailService;
                model._securityOptions = _securityOptions;
                model.EmailTemplateID  = ID;
                model._user            = User;

                await model.PopulateDetails();
            }
            catch (Exception ex)
            {
                HelperFunctions.Log(_context, PublicEnums.LogLevel.LEVEL_EXCEPTION, "Controllers.MasterDataController.EmailTemplateDetails", ex.Message, User, ex);
                ViewBag.Error = "An error occurred while loading data";
            }

            //Set message if redirected from save
            if (Success)
            {
                ViewBag.Success = "Email Template updated successfully";
            }

            ViewData.Model = model;

            return(View());
        }
Ejemplo n.º 6
0
        public static bool Send(string toEmail, EmailTemplateViewModel template)
        {
            try
            {
                var smtp = new SmtpClient();
                smtp.Host                  = Constant.SMTP.Host;
                smtp.Port                  = Constant.SMTP.Port;
                smtp.EnableSsl             = Constant.SMTP.IsSSLEnable;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = true;
                smtp.Credentials           = new NetworkCredential(Constant.SMTP.Username, Constant.SMTP.Password);

                using (var message = new MailMessage())
                {
                    message.From = new MailAddress(Constant.SMTP.From);
                    message.To.Add(new MailAddress(toEmail));
                    message.Bcc.Add(new MailAddress(Constant.SMTP.From));
                    message.Subject    = template.Subject;
                    message.Body       = template.Body;
                    message.IsBodyHtml = true;
                    message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;//– This is for set delivery notification mail On Failure

                    smtp.Send(message);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public ActionResult EditPost(EmailTemplateViewModel model)
        {
            if (!this.services.Authorizer.Authorize(Permissions.BasicDataPermission))
            {
                return new HttpUnauthorizedResult();
            }

            if (!this.ModelState.IsValid)
            {
                model = model ?? new EmailTemplateViewModel();
                this.FillByTypeItems(model.Types, null);
                return this.View("Edit", model);
            }

            var emailTemplate = this.emailTemplateRepository.Table.FirstOrDefault(c => c.Id == model.EmailTemplateId);

            if (emailTemplate == null)
            {
                this.ModelState.AddModelError("Id", this.T("There is no emailTemplate with the given Id").ToString());
                return this.View(model);
            }

            emailTemplate.Name = model.Name;
            emailTemplate.TypeId = model.TypeId;
            emailTemplate.Body = model.Text;
            emailTemplate.Subject = model.Subject;
            this.emailTemplateRepository.Flush();

            return RedirectToAction("Index");
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Edit(string name, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, EmailTemplatesPermissions.ManageEmailTemplates))
            {
                return(Unauthorized());
            }

            var templatesDocument = await _emailTemplatesManager.GetTemplatesDocumentAsync();

            if (!templatesDocument.Templates.ContainsKey(name))
            {
                return(RedirectToAction("Create", new { name, returnUrl }));
            }

            var template = templatesDocument.Templates[name];

            var model = new EmailTemplateViewModel
            {
                //AdminTemplates = adminTemplates,
                Name        = name,
                Content     = template.Content,
                Description = template.Description
            };

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        public ActionResult CreatePost(EmailTemplateViewModel model)
        {
            if (!this.services.Authorizer.Authorize(Permissions.BasicDataPermission))
            {
                return new HttpUnauthorizedResult();
            }

            if (!this.ModelState.IsValid)
            {
                model = model ?? new EmailTemplateViewModel();
                this.FillByTypeItems(model.Types, null);
                return this.View("Create", model);
            }

            EmailTemplateRecord emailTemplate = new EmailTemplateRecord();

            emailTemplate.Name = model.Name;
            emailTemplate.TypeId = model.TypeId;
            emailTemplate.Body = model.Text;
            emailTemplate.Subject = model.Subject;

            this.emailTemplateRepository.Create(emailTemplate);
            this.emailTemplateRepository.Flush();

            return RedirectToAction("Index");
        }
Ejemplo n.º 10
0
        public ActionResult Index()
        {
            var awards = _awardService.GetAllAwards().Select(x => new AwardViewModel()
            {
                AwardId    = x.Id,
                AwardCode  = x.Code,
                AwardTitle = x.Name
            }
                                                             ).ToList();

            var emailTemplateViewModel = new EmailTemplateViewModel()
            {
                Awards = awards
            };
            var emailTemplates = _emailTemplateService.GetAllTemplates();

            foreach (var template in emailTemplates)
            {
                emailTemplateViewModel.ProcessesViewModel.Add(new ProcessesViewModel()
                {
                    Id = template.Id, Name = template.TemplateName
                });
            }

            return(View(emailTemplateViewModel));
        }
Ejemplo n.º 11
0
        public override bool LoadModel(MassEmail em, EmailTemplateViewModel template, CompanyUser user)
        {
            LoadBaseFeature(em, template, user);
            //template.Models.
            DateTime datefrom = DateTime.Now;

            datefrom = datefrom.AddDays(em.DayFrom);
            DateTime dateto = DateTime.Now;
            int      add    = em.DayFrom + em.DayTo;

            dateto = dateto.AddDays(add);
            if (datefrom.Ticks == 0)
            {
                datefrom = DateTime.Today;
            }
            if (dateto.Ticks == 0)
            {
                dateto = DateTime.Today.AddDays(3);
            }
            datefrom = datefrom.ResetHMS();
            dateto   = dateto.ResetHMS();
            //this.DateCycle(em, template, (em, template, dt) => {
            //    template.Models.Add(dt, _mailRepo.ReportRepository.CompanyDayProduction(datefrom, dateto, _companyid));
            //});
            template.Models.Add(datefrom, _mailRepo.ReportRepository.CompanyDayProduction(datefrom, dateto, _companyid));

            return(true);
        }
Ejemplo n.º 12
0
        static void sendEmail(Dictionary <string, string> data, byte[] TemplateObject)
        {
            //Lấy TemplateObject chuyển thành EmailTemplate
            EmailTemplateViewModel emailTemplateViewModel = Erp.BackOffice.Helpers.Common.ByteArrayToObject(TemplateObject) as EmailTemplateViewModel;

            //Điền dữ liệu từ dòng dữ liệu vừa được tạo ra
            emailTemplateViewModel.From      = replaceData(emailTemplateViewModel.From, data);
            emailTemplateViewModel.To        = replaceData(emailTemplateViewModel.To, data);
            emailTemplateViewModel.Cc        = replaceData(emailTemplateViewModel.Cc, data);
            emailTemplateViewModel.Bcc       = replaceData(emailTemplateViewModel.Bcc, data);
            emailTemplateViewModel.Subject   = replaceData(emailTemplateViewModel.Subject, data);
            emailTemplateViewModel.Body      = replaceData(emailTemplateViewModel.Body, data);
            emailTemplateViewModel.Regarding = replaceData(emailTemplateViewModel.Regarding, data);

            //Thực hiện gửi mail bình thường
            Erp.BackOffice.Helpers.Common.SendEmailAttachment(
                Erp.BackOffice.Helpers.Common.GetSetting("Email")
                , Erp.BackOffice.Helpers.Common.GetSetting("EmailPassword")
                , emailTemplateViewModel.To
                , emailTemplateViewModel.Subject
                , emailTemplateViewModel.Body
                , emailTemplateViewModel.Cc
                , emailTemplateViewModel.Bcc
                , "Warehouse ELUTUS"
                );
        }
        /// <summary>
        /// If we add a template we add a type for it other wise we don't edit type at all its a hard coded thing to be used as a call for the email
        ///
        /// This service adds an email template to the system
        /// </summary>
        /// <param name="ViewModel"></param>
        public void AddEmailTemplate(EmailTemplateViewModel ViewModel)
        {
            EmailTemplateType type = new EmailTemplateType()
            {
                Key        = ViewModel.Key,
                Name       = ViewModel.Name,
                CreatedBy  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                CreatedOn  = DateTime.Now,
                ModifiedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                ModifiedOn = DateTime.Now
            };

            EmailTemplate template = new EmailTemplate()
            {
                EmailFrom  = ViewModel.From,
                Template   = ViewModel.Template,
                Subject    = ViewModel.Subject,
                CreatedBy  = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                CreatedOn  = DateTime.Now,
                ModifiedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                ModifiedOn = DateTime.Now
            };

            db.EmailTemplateTypes.Add(type);
            db.SaveChanges();
            template.TypeId = type.Id;
            db.EmailTemplates.Add(template);
            db.SaveChanges();
        }
Ejemplo n.º 14
0
 public ActionResult GetTemplate(int id)
 {
     try
     {
         using (var db = new ApplicationDbContext())
         {
             var template = db.Templates.Where(x => x.Id == id && x.IsActive && x.OrgId == IMSUserUtil.OrgId).SingleOrDefault();
             if (template == null)
             {
                 throw new Exception("Not Found!");
             }
             var model = new EmailTemplateViewModel
             {
                 Id      = template.Id,
                 Name    = template.Name,
                 Content = JsonConvert.DeserializeObject <EmailTemplateContentViewModel>(Encoding.UTF8.GetString(template.Content))
             };
             db.SaveChanges();
             return(Json(new ImsResult()
             {
                 Data = model
             }, JsonRequestBehavior.AllowGet));
         }
     }
     catch (Exception e)
     {
         return(Json(new ImsResult {
             Error = e.Message
         }, JsonRequestBehavior.AllowGet));
     }
 }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(View("ForgotPasswordConfirmation"));
                }

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account",
                                             new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                EmailTemplateViewModel mailTemplateVm = new EmailTemplateViewModel()
                {
                    Name        = user.Name,
                    LastName    = user.LastName,
                    CallbackUrl = callbackUrl
                };

                string templatePath = @"~\Views\EmailTemplates\ForgotPasswordEmailView.cshtml";
                await MailService.SendTemplateMessageAsync(model.Email, templatePath, mailTemplateVm, true);

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }
            return(View(model));
        }
        private string GenerateRepCommentsText(EmailTemplateViewModel item, HTMLParserService parser)
        {
            Hashtable blockVars = new Hashtable();

            blockVars.Add("RepComments", item.RepComments);
            string parsedHtml = parser.ParseBlock("RepComments", blockVars);

            return(parsedHtml);
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Register(RegisterViewModel registerForm)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerForm));
            }

            var user = new User
            {
                Email          = OptimizeText.OptimizeEmail(registerForm.Email),
                IsActive       = false,
                Name           = registerForm.Name,
                RegisterDate   = DateTime.Now,
                ActivationCode = Generator.GenerationUniqueName(),
                Password       = PasswordHelper.Hash(registerForm.Password),
                Avatar         = "default-avatar.png"
            };

            await _userService.AddUserAsync(user);

            var userRole = new UserRole
            {
                RoleId = 3,
                UserId = (await _userService.GetUserByEmailAsync(user.Email)).Id
            };

            await _permissionService.AddUserRoleAsync(userRole);

            #region Send Account Activation Email

            var emailTemplateViewModel = new EmailTemplateViewModel()
            {
                Name = user.Name,
                Url  = string.Concat(Request.Scheme, "://", Request.Host.ToUriComponent(),
                                     $"/Account/ActivateAccount/{user.ActivationCode}")
            };

            var email = new Email()
            {
                To      = user.Email,
                Subject = "فعال سازی حساب کاربری - تاپ لرن",
                Body    = await _viewRenderService.RenderToStringAsync("_AccountActivationTemplate", emailTemplateViewModel)
            };

            var emailSuccessfullySent = await _mailService.SendEmailAsync(email);

            if (!emailSuccessfullySent)
            {
                TempData["Error"] = "مشکلی پیش آمد، لطفا مجددا امتحان کنید";
                return(View(registerForm));
            }

            #endregion

            return(View("SuccessRegister", user));
        }
        /// <summary>
        /// Allows for alterations of the template but only just the template
        /// </summary>
        /// <param name="ViewModel"></param>
        public void EditEmailTemplate(EmailTemplateViewModel ViewModel)
        {
            var model = db.EmailTemplates.Single(o => o.Id == ViewModel.Id);

            model.EmailFrom  = ViewModel.From;
            model.Template   = ViewModel.Template;
            model.ModifiedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            model.ModifiedOn = DateTime.Now;
            db.SaveChanges();
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Create(EmailTemplateViewModel model, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, EmailTemplatesPermissions.ManageEmailTemplates))
            {
                return(Unauthorized());
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(new EmailTemplateViewModel()));
        }
Ejemplo n.º 20
0
        protected virtual void  DateCycle(MassEmail em, EmailTemplateViewModel template, Action <MassEmail, EmailTemplateViewModel, DateTime> action)
        {
            DateTime dayfrom = DateTime.Today.AddDays(em.DayFrom);
            DateTime dayto   = DateTime.Today.AddDays(em.DayTo);

            for (DateTime dt = dayfrom; dt <= dayto; dt = dt.AddDays(1))
            {
                action(em, template, dt);
            }
        }
 public ActionResult Edit(EmailTemplateViewModel model)
 {
     if (ModelState.IsValid)
     {
         var emailTemplate = model.ToEntity(db);
         db.SaveChanges();
         ShowGenericSavedMessage();
         return(RedirectToAction("Index"));
     }
     return(View(model));
 }
Ejemplo n.º 22
0
        public override bool LoadModel(MassEmail em, EmailTemplateViewModel template, CompanyUser user)
        {
            LoadBaseFeature(em, template, user);
            //this.DateCycle(em, template, (em, template, dt) => {
            //    template.Models.Add(dt, _mailRepo.ReportRepository.EmailWeekInvoice(dt, _companyid,user));
            //});
            DateTime dt = DateTime.Now;

            template.Models.Add(dt, _mailRepo.ReportRepository.EmailWeekInvoice(dt, _companyid, user));
            return(true);
        }
Ejemplo n.º 23
0
 protected virtual ExecutionModel GetExecutionModel(MassEmail em, EmailTemplateViewModel template, CompanyUser user)
 {
     return(new ExecutionModel()
     {
         DateFrom = DateTime.Today.AddDays(em.DayFrom),
         DateTo = DateTime.Today.AddDays(em.DayTo),
         CompanyId = _companyid,
         UserFriendlyName = user?.NameSurname,
         UserChildFriendlyName = user?.ChildNameSurname
     });
 }
        public ActionResult Create()
        {
            if (!this.services.Authorizer.Authorize(Permissions.BasicDataPermission))
            {
                return new HttpUnauthorizedResult();
            }

            var model = new EmailTemplateViewModel();
            this.FillByTypeItems(model.Types, null);

            return this.View(model);
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> CreatePost(EmailTemplateViewModel model, string submit, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageEmailTemplates))
            {
                return(Forbid());
            }

            ViewData["ReturnUrl"] = returnUrl;

            var templatesDocument = await _templatesManager.GetEmailTemplatesDocumentAsync();

            if (templatesDocument.Templates.Values.Any(x => x.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase)))
            {
                ModelState.AddModelError(nameof(EmailTemplateViewModel.Name), S["An email template with the same name already exists."]);
            }

            if (ModelState.IsValid)
            {
                var id = IdGenerator.GenerateId();

                var template = new EmailTemplate
                {
                    Name                 = model.Name,
                    Description          = model.Description,
                    AuthorExpression     = model.AuthorExpression,
                    SenderExpression     = model.SenderExpression,
                    ReplyToExpression    = model.ReplyToExpression,
                    RecipientsExpression = model.RecipientsExpression,
                    CCExpression         = model.CCExpression,
                    BCCExpression        = model.BCCExpression,
                    SubjectExpression    = model.SubjectExpression,
                    Body                 = model.Body,
                    IsBodyHtml           = model.IsBodyHtml,
                };

                await _templatesManager.UpdateTemplateAsync(id, template);

                _notifier.Success(H["The \"{0}\" email template has been created.", model.Name]);

                if (submit == "SaveAndContinue")
                {
                    return(RedirectToAction(nameof(Edit), new { id, returnUrl }));
                }
                else
                {
                    return(RedirectToReturnUrlOrIndex(returnUrl));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 26
0
        // EDIT
        public ActionResult Edit(int id)
        {
            var template = _context.EmailTemplates.SingleOrDefault(t => t.MailTemplateId == id);

            if (template == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new EmailTemplateViewModel(template);

            return(View("EmailTemplateForm", viewModel));
        }
Ejemplo n.º 27
0
        public async Task <NotificationEmail> CreateMyWondersEmailAndSend(AspNetUser user)
        {
            string emailPlainText = "MyWonders = \n";
            string emailHtmlText  = "";

            if (!useDefaultEmail)
            {
                _emailToUse = user.Email;
            }

            var email = new NotificationEmail
            {
                Created        = DateTime.UtcNow,
                RecipientEmail = _emailToUse,
                RecipientName  = user.UserName
            };

            var amountToSkip  = user.MyWonders.Count <= NumberOfWonders ? 0 : user.MyWonders.Count - NumberOfWonders;
            var recentWonders = user.MyWonders.Where(x => x.Archived != true).Skip(amountToSkip).Reverse();
            //var recentWonders = user.MyWonders.Skip(user.MyWonders.Count - NumberOfWonders);

            var model = new EmailTemplateViewModel();

            model.User    = Mapper.Map <UserModel>(user);
            model.Wonders = Mapper.Map <List <DealModel> >(recentWonders);

            //TODO: move these to config properties
            model.UrlString       = "https://cms.thewonderapp.co/content/images/";
            model.UnsubscribeLink = "mailto:[email protected] ";

            foreach (var wonder in recentWonders)
            {
                emailPlainText += wonder.Title + "\n";
            }


            Template templateToUse = _dataContext.Templates.FirstOrDefault(t => t.Name.Equals("MyWondersEmail"));

            if (templateToUse != null)
            {
                emailHtmlText = await LoadTemplate(templateToUse.File.Trim(), model);

                email.Template_Id = templateToUse.Id;
            }
            else
            {
                emailHtmlText = emailPlainText;
            }

            return(await SendEmail(email, emailPlainText, emailHtmlText));
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> Edit(EmailTemplateViewModel model, string submit, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageEmailTemplates))
            {
                return(Forbid());
            }

            var templatesDocument = await _templatesManager.LoadEmailTemplatesDocumentAsync();

            if (ModelState.IsValid && templatesDocument.Templates.Any(x => x.Key != model.Id && x.Value.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase)))
            {
                ModelState.AddModelError(nameof(EmailTemplateViewModel.Name), S["An email template with the same name already exists."]);
            }

            if (!templatesDocument.Templates.ContainsKey(model.Id))
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var template = new EmailTemplate
                {
                    Name                 = model.Name,
                    Description          = model.Description,
                    AuthorExpression     = model.AuthorExpression,
                    ReplyToExpression    = model.ReplyToExpression,
                    SenderExpression     = model.SenderExpression,
                    RecipientsExpression = model.RecipientsExpression,
                    CCExpression         = model.CCExpression,
                    BCCExpression        = model.BCCExpression,
                    SubjectExpression    = model.SubjectExpression,
                    Body                 = model.Body,
                    IsBodyHtml           = model.IsBodyHtml,
                };

                await _templatesManager.RemoveTemplateAsync(model.Id);

                await _templatesManager.UpdateTemplateAsync(model.Id, template);

                if (submit != "SaveAndContinue")
                {
                    return(RedirectToReturnUrlOrIndex(returnUrl));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Ejemplo n.º 29
0
        public IActionResult InsertEmailTemplate([FromBody] EmailTemplateViewModel model)
        {
            try
            {
                var user = HttpContext.Session.Get <UserViewModel>(Constants.SessionKeyUserInfo);

                var data = _emailTemplateHandler.InsertEmailTemplate(model, Convert.ToString(user.UserId));

                return(Json(data));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message));
            }
        }
Ejemplo n.º 30
0
        public override bool LoadModel(MassEmail em, EmailTemplateViewModel template, CompanyUser user)
        {
            LoadBaseFeature(em, template, user);
            this.DateCycle(em, template, (em, template, dt) => {
                template.Models.Add(dt, _mailRepo.ReportRepository.CompanyComplexMenu(dt, dt, _companyid));
            });

            /*
             * DateTime dayfrom = DateTime.Today.AddDays(em.DayFrom);
             * DateTime dayto = DateTime.Today.AddDays(em.DayTo);
             * for (DateTime dt = dayfrom; dt<= dayto; dt = dt.AddDays(1)) {
             *  template.Models.Add(dt, _mailRepo.ReportRepository.CompanyComplexMenu(dt, dt, _companyid));
             * }*/
            return(true);
        }
        public NotificationsEventTypesDto GetNotificationPreviewByID(int id, HttpContext context)
        {
            NotificationsEventType eventType = _notificationEventTypes.Single(x => x.EventTypeID.Equals(id));

            EmailTemplateViewModel model = new EmailTemplateViewModel
            {
                Subject = eventType.EmailSubject,
                Body = eventType.EmailBody,
            };

            string mergeTagBody = EmailManager.RenderBody("~/Views/Emails/EmailTemplate.cshtml", model, context).Html;
            foreach (KeyValuePair<string, string> item in MergeTag.Tags)
                mergeTagBody = mergeTagBody.Replace(item.Key, item.Value);

            return new NotificationsEventTypesDto()
            {
                Name = eventType.Name,
                EmailBody = mergeTagBody,
                EmailSubject = eventType.EmailSubject
            };
        }