protected virtual void UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(mt,
                                                           x => x.BccEmailAddresses,
                                                           localized.BccEmailAddresses,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(mt,
                                                           x => x.Subject,
                                                           localized.Subject,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(mt,
                                                           x => x.Body,
                                                           localized.Body,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(mt,
                                                           x => x.EmailAccountId,
                                                           localized.EmailAccountId,
                                                           localized.LanguageId);
            }
        }
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
                //locales
                UpdateLocales(messageTemplate, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                return continueEditing ? RedirectToAction("Edit", messageTemplate.Id) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(ea.ToModel());
            return View(model);
        }
        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");

            var model = new MessageTemplateModel
            {
                BccEmailAddresses = messageTemplate.BccEmailAddresses,
                Body = messageTemplate.Body,
                EmailAccountId = messageTemplate.EmailAccountId,
                Id = messageTemplate.Id,
                IsActive = messageTemplate.IsActive,
                Name = messageTemplate.Name,
                Subject = messageTemplate.Subject
            };
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(new EmailAccountModel
                {
                    DisplayName = ea.DisplayName,
                    Email = ea.Email,
                    EnableSsl = ea.EnableSsl,
                    Host = ea.Host,
                    Id = ea.Id,
                    Password = ea.Password,
                    Port = ea.Port,
                    UseDefaultCredentials = ea.UseDefaultCredentials,
                    Username = ea.Username
                });
            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.BccEmailAddresses = messageTemplate.GetLocalized(x => x.BccEmailAddresses, languageId, false, false);
                locale.Subject = messageTemplate.GetLocalized(x => x.Subject, languageId, false, false);
                locale.Body = messageTemplate.GetLocalized(x => x.Body, languageId, false, false);

                var emailAccountId = messageTemplate.GetLocalized(x => x.EmailAccountId, languageId, false, false);
                locale.EmailAccountId = emailAccountId > 0 ? emailAccountId : _emailAccountSettings.DefaultEmailAccountId;
            });

            return View(model);
        }
Ejemplo n.º 4
0
        public void UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            foreach (var localized in model.Locales)
            {
                int lid = localized.LanguageId;

                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment1FileId, lid, false, false), localized.Attachment1FileId, true);
                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment2FileId, lid, false, false), localized.Attachment2FileId, true);
                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment3FileId, lid, false, false), localized.Attachment3FileId, true);

                _localizedEntityService.SaveLocalizedValue(mt, x => x.BccEmailAddresses, localized.BccEmailAddresses, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Subject, localized.Subject, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Body, localized.Body, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.EmailAccountId, localized.EmailAccountId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment1FileId, localized.Attachment1FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment2FileId, localized.Attachment2FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment3FileId, localized.Attachment3FileId, lid);
            }
        }
Ejemplo n.º 5
0
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
            {
                return(AccessDeniedView());
            }

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);

                //Sites
                _siteMappingService.SaveSiteMappings <MessageTemplate>(messageTemplate, model.SelectedSiteIds);

                //locales
                UpdateLocales(messageTemplate, model);

                NotifySuccess(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                return(continueEditing ? RedirectToAction("Edit", messageTemplate.Id) : RedirectToAction("List"));
            }


            //If we got this far, something failed, redisplay form
            FillTokensTree(model.TokensTree, _messageTokenProvider.GetListOfAllowedTokens());

            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
            {
                model.AvailableEmailAccounts.Add(ea.ToModel());
            }

            //Site
            PrepareSitesMappingModel(model, messageTemplate, true);
            return(View(model));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Create(MessageTemplateModel model, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                var messageTemplate = model.ToEntity();
                //attached file
                if (!model.HasAttachedDownload)
                {
                    messageTemplate.AttachedDownloadId = "";
                }
                if (model.SendImmediately)
                {
                    messageTemplate.DelayBeforeSend = null;
                }

                await _messageTemplateService.InsertMessageTemplate(messageTemplate);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.AddNew"));

                if (continueEditing)
                {
                    //selected tab
                    await SaveSelectedTabIndex();

                    return(RedirectToAction("Edit", new { id = messageTemplate.Id }));
                }
                return(RedirectToAction("List"));
            }


            //If we got this far, something failed, redisplay form
            model.HasAttachedDownload = !String.IsNullOrEmpty(model.AttachedDownloadId);
            model.AllowedTokens       = _messageTokenProvider.GetListOfAllowedTokens();
            //available email accounts
            foreach (var ea in await _emailAccountService.GetAllEmailAccounts())
            {
                model.AvailableEmailAccounts.Add(ea.ToModel());
            }
            //Store
            await model.PrepareStoresMappingModel(null, _storeService, true);

            return(View(model));
        }
Ejemplo n.º 7
0
        protected virtual void PrepareStoresMappingModel(MessageTemplateModel model, MessageTemplate messageTemplate, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            model.AvailableStores = _storeService
                                    .GetAllStores()
                                    .Select(s => s.ToModel())
                                    .ToList();
            if (!excludeProperties)
            {
                if (messageTemplate != null)
                {
                    model.SelectedStoreIds = messageTemplate.Stores.ToArray();
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Prepare message template model
        /// </summary>
        /// <param name="model">Message template model</param>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>Message template model</returns>
        public virtual MessageTemplateModel PrepareMessageTemplateModel(MessageTemplateModel model,
                                                                        MessageTemplate messageTemplate, bool excludeProperties = false)
        {
            Action <MessageTemplateLocalizedModel, int> localizedModelConfiguration = null;

            if (messageTemplate != null)
            {
                //fill in model values from the entity
                model = model ?? messageTemplate.ToModel <MessageTemplateModel>();

                //define localized model configuration action
                localizedModelConfiguration = (locale, languageId) =>
                {
                    locale.BccEmailAddresses = _localizationService.GetLocalized(messageTemplate, entity => entity.BccEmailAddresses, languageId, false, false);
                    locale.Subject           = _localizationService.GetLocalized(messageTemplate, entity => entity.Subject, languageId, false, false);
                    locale.Body           = _localizationService.GetLocalized(messageTemplate, entity => entity.Body, languageId, false, false);
                    locale.EmailAccountId = _localizationService.GetLocalized(messageTemplate, entity => entity.EmailAccountId, languageId, false, false);

                    //prepare available email accounts
                    _baseAdminModelFactory.PrepareEmailAccounts(locale.AvailableEmailAccounts,
                                                                defaultItemText: _localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Fields.EmailAccount.Standard"));
                };
            }

            model.SendImmediately     = !model.DelayBeforeSend.HasValue;
            model.HasAttachedDownload = model.AttachedDownloadId > 0;

            var allowedTokens = string.Join(", ", _messageTokenProvider.GetListOfAllowedTokens(_messageTokenProvider.GetTokenGroups(messageTemplate)));

            model.AllowedTokens = $"{allowedTokens}{Environment.NewLine}{Environment.NewLine}" +
                                  $"{_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Tokens.ConditionalStatement")}{Environment.NewLine}";

            //prepare localized models
            if (!excludeProperties)
            {
                model.Locales = _localizedModelFactory.PrepareLocalizedModels(localizedModelConfiguration);
            }

            //prepare available email accounts
            _baseAdminModelFactory.PrepareEmailAccounts(model.AvailableEmailAccounts);

            return(model);
        }
Ejemplo n.º 9
0
        protected virtual void PrepareStoresMappingModel(MessageTemplateModel model, MessageTemplate messageTemplate, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (!excludeProperties && messageTemplate != null)
                model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(messageTemplate).ToList();

            var allStores = _storeService.GetAllStores();
            foreach (var store in allStores)
            {
                model.AvailableStores.Add(new SelectListItem
                {
                    Text = store.Name,
                    Value = store.Id.ToString(),
                    Selected = model.SelectedStoreIds.Contains(store.Id)
                });
            }
        }
Ejemplo n.º 10
0
        private Message AssembleMessageForPayerSummary
            (StringBuilder orderDetails, int confirmationId, string payer)
        {
            MessageTemplateModel template = _messageTemplateLogic.ReadForKey
                                                (Constants.MESSAGE_TEMPLATE_MULTI_PAYMENTCONFIRMATION);

            Message message = new Message();

            message.BodyIsHtml     = template.IsBodyHtml;
            message.MessageSubject = template.Subject;
            // the following assembles the template for the body of the payer summary
            message.MessageBody = template.Body.Inject(new
            {
                UserName          = payer,
                ConfirmationId    = confirmationId,
                PaymentCollection = orderDetails.ToString()
            });
            message.NotificationType = NotificationType.PaymentConfirmation;
            return(message);
        }
Ejemplo n.º 11
0
        public MessageTemplateModel FindMessageTemplateModel(int companyId, MessageTemplateType templateId, bool bCreateEmptyIfNotfound = true)
        {
            MessageTemplateModel model = null;

            var et = db.FindMessageTemplate(companyId, templateId);

            if (et == null)
            {
                if (bCreateEmptyIfNotfound)
                {
                    model = new MessageTemplateModel();
                }
            }
            else
            {
                model = MapToModel(et);
            }

            return(model);
        }
Ejemplo n.º 12
0
        public IActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
            {
                return(AccessDeniedView());
            }

            var model = new MessageTemplateModel();

            //Stores
            PrepareStoresMappingModel(model, null, false);
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
            {
                model.AvailableEmailAccounts.Add(ea.ToModel());
            }

            return(View(model));
        }
        /// <summary>
        /// Prepares the reset password email message.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="MessageTemplateModel">The email template model.</param>
        /// <param name="email">The email.</param>
        /// <param name="resetIdentifier">The reset identifier.</param>
        /// <returns></returns>
        private EmailMessageModel PrepareResetPasswordEmailMessage(UserModel user, MessageTemplateModel MessageTemplateModel, string email, Guid resetIdentifier)
        {
            var emailMessage      = new EmailMessageModel();
            var retrievedSettings = GetFromEmailSettings();

            var webAppUrl = retrievedSettings.FirstOrDefault(f => f.SettingsID == (int)Setting.WebServerUrl).Value;

            emailMessage.Subject    = MessageTemplateModel.EmailSubject;
            emailMessage.Body       = string.Format(MessageTemplateModel.MessageBody, user.FirstName, webAppUrl, resetIdentifier);
            emailMessage.IsBodyHtml = MessageTemplateModel.IsHtmlBody;

            emailMessage.To.Add(new EmailAddressModel()
            {
                EmailAddress = email, DisplayName = string.Format("{0} {1}", user.FirstName, user.LastName)
            });

            emailMessage.From.EmailAddress = retrievedSettings.FirstOrDefault(f => f.SettingsID == (int)Setting.FromEmail).Value;
            emailMessage.From.DisplayName  = retrievedSettings.FirstOrDefault(d => d.SettingsID == (int)Setting.FromDisplayName).Value;
            return(emailMessage);
        }
        private EmailMessageModel PrepareNewUserEmailMessage(MessageTemplateModel messageTemplate, UserModel user)
        {
            var emailMessage      = new EmailMessageModel();
            var retrievedSettings = GetFromEmailSettings();
            var webServerUrl      = retrievedSettings.FirstOrDefault(f => f.SettingsID == (int)Setting.WebServerUrl).Value;

            emailMessage.Subject    = messageTemplate.EmailSubject;
            emailMessage.Body       = String.Format(messageTemplate.MessageBody, user.FirstName + " " + user.LastName, user.UserName, user.Password, webServerUrl);
            emailMessage.IsBodyHtml = messageTemplate.IsHtmlBody;

            emailMessage.To.Add(new EmailAddressModel()
            {
                EmailAddress = user.PrimaryEmail, DisplayName = user.PrimaryEmail
            });

            emailMessage.From.EmailAddress = retrievedSettings.FirstOrDefault(f => f.SettingsID == (int)Setting.FromEmail).Value;
            emailMessage.From.DisplayName  = retrievedSettings.FirstOrDefault(d => d.SettingsID == (int)Setting.FromDisplayName).Value;

            return(emailMessage);
        }
        public ActionResult CopyTemplate(MessageTemplateModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                return RedirectToAction("List");

            try
            {
                var newMessageTemplate = _messageTemplateService.CopyMessageTemplate(messageTemplate);
                NotifySuccess("The message template has been copied successfully");
                return RedirectToAction("Edit", new { id = newMessageTemplate.Id });
            }
            catch (Exception exc)
            {
                NotifyError(exc.Message);
                return RedirectToAction("Edit", new { id = model.Id });
            }
        }
Ejemplo n.º 16
0
        public ActionResult CopyTemplate(MessageTemplateModel model)
        {
            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                return(RedirectToAction("List"));
            }

            try
            {
                var newMessageTemplate = _messageTemplateService.CopyMessageTemplate(messageTemplate);
                NotifySuccess(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.SuccessfullyCopied"));
                return(RedirectToAction("Edit", new { id = newMessageTemplate.Id }));
            }
            catch (Exception exc)
            {
                NotifyError(exc.Message);
                return(RedirectToAction("Edit", new { id = model.Id }));
            }
        }
Ejemplo n.º 17
0
        public void UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            foreach (var localized in model.Locales)
            {
                int lid = localized.LanguageId;

                // Attachments: handle tracking of localized media file uploads
                var attachments = new List <(int?prevId, int?curId, string prop)>(3)
                {
                    (mt.GetLocalized(x => x.Attachment1FileId, lid, false, false), localized.Attachment1FileId, $"Attachment1FileId[{lid}]"),
                    (mt.GetLocalized(x => x.Attachment2FileId, lid, false, false), localized.Attachment2FileId, $"Attachment2FileId[{lid}]"),
                    (mt.GetLocalized(x => x.Attachment3FileId, lid, false, false), localized.Attachment3FileId, $"Attachment3FileId[{lid}]")
                };

                foreach (var attach in attachments)
                {
                    if (attach.prevId != attach.curId)
                    {
                        if (attach.prevId.HasValue)
                        {
                            _mediaTracker.Untrack(mt, attach.prevId.Value, attach.prop);
                        }
                        if (attach.curId.HasValue)
                        {
                            _mediaTracker.Track(mt, attach.curId.Value, attach.prop);
                        }
                    }
                }

                _localizedEntityService.SaveLocalizedValue(mt, x => x.To, localized.To, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.ReplyTo, localized.ReplyTo, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.BccEmailAddresses, localized.BccEmailAddresses, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Subject, localized.Subject, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Body, localized.Body, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.EmailAccountId, localized.EmailAccountId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment1FileId, localized.Attachment1FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment2FileId, localized.Attachment2FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment3FileId, localized.Attachment3FileId, lid);
            }
        }
        private Message MakeConfirmationMessage(OrderConfirmationNotification notification, Customer customer, StringBuilder originalOrderInfo, decimal totalAmount)
        {
            string  invoiceNumber         = GetInvoiceNumber(notification, customer);
            Message message               = new Message();
            MessageTemplateModel template = _messageTemplateLogic.ReadForKey(MESSAGE_TEMPLATE_ORDERCONFIRMATION);

            message.MessageSubject = template.Subject.Inject(new {
                OrderStatus    = "Order Confirmation",
                CustomerNumber = customer.CustomerNumber,
                CustomerName   = customer.CustomerName,
                InvoiceNumber  = invoiceNumber
            });
            StringBuilder header = _messageTemplateLogic.BuildHeader("Thank you for your order", customer);

            message.MessageBody += template.Body.Inject(new {
                NotifHeader            = header.ToString(),
                InvoiceNumber          = invoiceNumber,
                ShipDate               = notification.OrderChange.ShipDate,
                Count                  = notification.OrderChange.Items.Count,
                PcsCount               = BuildPieceCount(notification),
                Total                  = totalAmount.ToString("f2"),
                PurchaseOrder          = notification.OrderChange.OrderName,
                OrderConfirmationItems = originalOrderInfo.ToString()
            });
            message.BodyIsHtml       = template.IsBodyHtml;
            message.CustomerNumber   = customer.CustomerNumber;
            message.CustomerName     = customer.CustomerName;
            message.BranchId         = customer.CustomerBranch;
            message.NotificationType = NotificationType.OrderConfirmation;

            //AlternateView avHtml = AlternateView.CreateAlternateViewFromString
            //    (message.MessageBody, null, MediaTypeNames.Text.Html);

            //// Create a LinkedResource object for each embedded image
            //LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
            //pic1.ContentId = "Pic1";
            //avHtml.LinkedResources.Add(pic1);

            return(message);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates email message from user feeedback notification.
        /// </summary>
        /// <param name="notification"></param>
        /// <returns></returns>
        private Message CreateEmailMessageForNotification(UserFeedbackNotification notification)
        {
            Message message = new Message();
            MessageTemplateModel template = _messageTemplateLogic.ReadForKey(MESSAGE_TEMPLATE_USERFEEDBACK);

            var context      = notification.Context;
            var userFeedback = notification.UserFeedback;

            message.MessageSubject = template.Subject.Inject(new
            {
                CustomerNumber = context.CustomerNumber,
                CustomerName   = context.CustomerName,
                Audience       = userFeedback.Audience.ToString(),
            });

            Customer customer = _customerRepository.GetCustomerByCustomerNumber(notification.CustomerNumber, notification.BranchId);

            StringBuilder header = _messageTemplateLogic.BuildHeader("Feedback from ", customer);

            message.MessageBody += template.Body.Inject(new
            {
                NotifHeader = header.ToString(),

                UserFirstName      = context.UserFirstName,
                UserLastName       = context.UserLastName,
                SourceEmailAddress = context.SourceEmailAddress,
                SalesRepName       = context.SalesRepName,

                Subject = userFeedback.Subject,
                Content = userFeedback.Content,
            });

            message.BodyIsHtml       = template.IsBodyHtml;
            message.CustomerNumber   = context.CustomerNumber;
            message.CustomerName     = context.CustomerName;
            message.BranchId         = context.BranchId;
            message.NotificationType = NotificationType.UserFeedback;

            return(message);
        }
Ejemplo n.º 20
0
        public IActionResult CopyTemplate(MessageTemplateModel model)
        {
            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                //No message template found with the specified id
                return(RedirectToAction("List"));
            }

            try
            {
                var newMessageTemplate = _messageTemplateService.CopyMessageTemplate(messageTemplate);
                SuccessNotification("The message template has been copied successfully");
                return(RedirectToAction("Edit", new { id = newMessageTemplate.Id }));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc.Message);
                return(RedirectToAction("Edit", new { id = model.Id }));
            }
        }
Ejemplo n.º 21
0
        public ActionResult CopyTemplate(MessageTemplateModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");

            try
            {
                var newMessageTemplate = _messageTemplateService.CopyMessageTemplate(messageTemplate);
                SuccessNotification("The message template has been copied successfully");
                return RedirectToAction("Edit", new { id = newMessageTemplate.Id });
            }
            catch (Exception exc)
            {
                ErrorNotification(exc.Message);
                return RedirectToAction("Edit", new { id = model.Id });
            }
        }
        private Message MakeRejectedMessage(OrderConfirmationNotification notification, Customer customer)
        {
            MessageTemplateModel rejectTemplate = _messageTemplateLogic.ReadForKey(MESSAGE_TEMPLATE_ORDERREJECTED);
            Message message = new Message();

            message.MessageSubject = rejectTemplate.Subject.Inject(new {
                CustomerNumber = customer.CustomerNumber,
                CustomerName   = customer.CustomerName,
            });
            StringBuilder header = _messageTemplateLogic.BuildHeader("Order Rejected", customer);

            message.MessageBody = rejectTemplate.Body.Inject(new {
                NotifHeader         = header.ToString(),
                SpecialInstructions = notification.OrderChange.SpecialInstructions
            });
            message.BodyIsHtml       = rejectTemplate.IsBodyHtml;
            message.CustomerNumber   = customer.CustomerNumber;
            message.CustomerName     = customer.CustomerName;
            message.BranchId         = customer.CustomerBranch;
            message.NotificationType = NotificationType.OrderConfirmation;
            return(message);
        }
Ejemplo n.º 23
0
        protected virtual void SaveStoreMappings(MessageTemplate messageTemplate, MessageTemplateModel model)
        {
            messageTemplate.LimitedToStores = model.SelectedStoreIds.Any();

            var existingStoreMappings = _storeMappingService.GetStoreMappings(messageTemplate);

            #region Extensions  by QuanNH

            //stores
            var _workContext = Nop.Core.Infrastructure.EngineContext.Current.Resolve <Nop.Core.IWorkContext>();
            var allStores    = _storeService.GetAllStoresByEntityName(_workContext.CurrentCustomer.Id, "Stores");
            if (allStores.Count <= 0)
            {
                allStores = _storeService.GetAllStores();
            }

            #endregion
            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                    {
                        _storeMappingService.InsertStoreMapping(messageTemplate, store.Id);
                    }
                }
                else
                {
                    //remove store
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                    }
                }
            }
        }
        private void PrepareStoresMappingModel(MessageTemplateModel model, MessageTemplate messageTemplate, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            model.AvailableStores = _storeService
                                    .GetAllStores()
                                    .Select(s => s.ToModel())
                                    .ToList();
            if (!excludeProperties)
            {
                if (messageTemplate != null)
                {
                    model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(messageTemplate);
                }
                else
                {
                    model.SelectedStoreIds = new int[0];
                }
            }
        }
        public ActionResult Edit(MessageTemplateModel model)
        {
            var messageTemplate = _messageTemplateRepository.GetById(model.Id);

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                //always set IsNew to false when saving
                messageTemplate.IsNew = false;
                _messageTemplateRepository.Update(messageTemplate);

                //commit all changes
                this._dbContext.SaveChanges();

                //notification
                SuccessNotification(_localizationService.GetResource("Record.Saved"));
                return(new NullJsonResult());
            }
            else
            {
                return(Json(new { Errors = ModelState.SerializeErrors() }));
            }
        }
        protected virtual void SaveStoreMappings(MessageTemplate messageTemplate, MessageTemplateModel model)
        {
            messageTemplate.LimitedToStores = model.SelectedStoreIds.Any();

            var existingStoreMappings = _storeMappingService.GetStoreMappings(messageTemplate);
            var allStores = _storeService.GetAllStores();
            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                        _storeMappingService.InsertStoreMapping(messageTemplate, store.Id);
                }
                else
                {
                    //remove store
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                }
            }
        }
        private void BuildItemDetail(StringBuilder itemOrderInfo, OrderLineChange line, string priceInfo, string extPriceInfo, Product currentProduct)
        {
            MessageTemplateModel itemDetailTemplate = _messageTemplateLogic.ReadForKey(MESSAGE_TEMPLATE_ORDERITEMDETAIL);

            object lineData = null;

            if (currentProduct == null)
            {
                lineData = new {
                    ProductNumber      = line.ItemNumber,
                    ProductDescription = "Unknown",
                    Brand    = "Unknown",
                    Quantity = line.QuantityOrdered.ToString(),
                    Sent     = line.QuantityOrdered.ToString(),
                    Pack     = "Unknown",
                    Size     = "Unknown",
                    Price    = priceInfo,
                    Status   = line.OriginalStatus
                };
            }
            else
            {
                lineData = new {
                    ProductNumber      = line.ItemNumber,
                    ProductDescription = currentProduct.Name,
                    Brand    = currentProduct.Brand,
                    Quantity = line.QuantityOrdered.ToString(),
                    Sent     = line.QuantityOrdered.ToString(),
                    Pack     = currentProduct.Pack,
                    Size     = currentProduct.Size,
                    Price    = priceInfo,
                    Status   = line.OriginalStatus
                };
            }

            itemOrderInfo.Append(itemDetailTemplate.Body.Inject(lineData));
        }
Ejemplo n.º 28
0
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing, FormCollection form)
        {
            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);

                MediaHelper.UpdateDownloadTransientStateFor(messageTemplate, x => x.Attachment1FileId);
                MediaHelper.UpdateDownloadTransientStateFor(messageTemplate, x => x.Attachment2FileId);
                MediaHelper.UpdateDownloadTransientStateFor(messageTemplate, x => x.Attachment3FileId);

                _messageTemplateService.UpdateMessageTemplate(messageTemplate);

                SaveStoreMappings(messageTemplate, model.SelectedStoreIds);
                UpdateLocales(messageTemplate, model);

                Services.EventPublisher.Publish(new ModelBoundEvent(model, messageTemplate, form));

                NotifySuccess(T("Admin.ContentManagement.MessageTemplates.Updated"));
                return(continueEditing ? RedirectToAction("Edit", messageTemplate.Id) : RedirectToAction("List"));
            }

            model.AvailableEmailAccounts = _emailAccountService.GetAllEmailAccounts()
                                           .Select(x => x.ToModel())
                                           .ToList();

            PrepareLastModelTree(messageTemplate);
            PrepareStoresMappingModel(model, messageTemplate, true);

            return(View(model));
        }
Ejemplo n.º 29
0
        public IActionResult MessageList(MessageTemplateModel model)
        {
            var storeId          = _storeContext.ActiveStoreScopeConfiguration;
            var messageTemplates = _messageTemplateService.GetAllMessageTemplates(storeId);

            var gridModel = new DataSourceResult
            {
                Data = messageTemplates.Select(messageTemplate =>
                {
                    //standard template of message is edited in the admin area, SendinBlue template is edited in the SendinBlue account
                    var isStandardTemplate = !_genericAttributeService.GetAttribute <bool>(messageTemplate, SendinBlueDefaults.SendinBlueTemplateAttribute);
                    var templateId         = _genericAttributeService.GetAttribute <int>(messageTemplate, SendinBlueDefaults.TemplateIdAttribute);
                    var stores             = _storeService.GetAllStores()
                                             .Where(store => !messageTemplate.LimitedToStores || _storeMappingService.GetStoresIdsWithAccess(messageTemplate).Contains(store.Id))
                                             .Aggregate(string.Empty, (current, next) => $"{current}, {next.Name}").Trim(',');

                    return(new MessageTemplateModel
                    {
                        Id = messageTemplate.Id,
                        Name = messageTemplate.Name,
                        IsActive = messageTemplate.IsActive,
                        ListOfStores = stores,
                        TemplateTypeId = isStandardTemplate ? 0 : 1,
                        TemplateType = isStandardTemplate
                            ? _localizationService.GetResource("Plugins.Misc.SendinBlue.StandardTemplate")
                            : _localizationService.GetResource("Plugins.Misc.SendinBlue.SendinBlueTemplate"),
                        EditLink = isStandardTemplate
                            ? Url.Action("Edit", "MessageTemplate", new { id = messageTemplate.Id, area = AreaNames.Admin })
                            : $"{string.Format(SendinBlueDefaults.EditMessageTemplateUrl, templateId)}"
                    });
                }),
                Total = messageTemplates.Count
            };

            return(Json(gridModel));
        }
Ejemplo n.º 30
0
        protected virtual List <LocalizedProperty> UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            List <LocalizedProperty> localized = new List <LocalizedProperty>();

            foreach (var local in model.Locales)
            {
                localized.Add(new LocalizedProperty()
                {
                    LanguageId  = local.LanguageId,
                    LocaleKey   = "BccEmailAddresses",
                    LocaleValue = local.BccEmailAddresses
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId  = local.LanguageId,
                    LocaleKey   = "Subject",
                    LocaleValue = local.Subject
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId  = local.LanguageId,
                    LocaleKey   = "Body",
                    LocaleValue = local.Body
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId  = local.LanguageId,
                    LocaleKey   = "EmailAccountId",
                    LocaleValue = local.EmailAccountId.ToString()
                });
            }
            return(localized);
        }
        public virtual IActionResult CopyTemplate(MessageTemplateModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            //try to get a message template with the specified id
            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                return RedirectToAction("List");

            try
            {
                var newMessageTemplate = _messageTemplateService.CopyMessageTemplate(messageTemplate);

                _notificationService.SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Copied"));

                return RedirectToAction("Edit", new { id = newMessageTemplate.Id });
            }
            catch (Exception exc)
            {
                _notificationService.ErrorNotification(exc.Message);
                return RedirectToAction("Edit", new { id = model.Id });
            }
        }
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
            {
                return(AccessDeniedView());
            }

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                //No message template found with the specified id
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
                //locales
                UpdateLocales(messageTemplate, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                return(continueEditing ? RedirectToAction("Edit", messageTemplate.Id) : RedirectToAction("List"));
            }


            //If we got this far, something failed, redisplay form
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
            {
                model.AvailableEmailAccounts.Add(ea.ToModel());
            }
            return(View(model));
        }
Ejemplo n.º 33
0
 public static MessageTemplate ToEntity(this MessageTemplateModel model, MessageTemplate destination)
 {
     return(model.MapTo(destination));
 }
        protected virtual List<LocalizedProperty> UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            List<LocalizedProperty> localized = new List<LocalizedProperty>();
            foreach (var local in model.Locales)
            {
                localized.Add(new LocalizedProperty()
                {
                    LanguageId = local.LanguageId,
                    LocaleKey = "BccEmailAddresses",
                    LocaleValue = local.BccEmailAddresses
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId = local.LanguageId,
                    LocaleKey = "Subject",
                    LocaleValue = local.Subject
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId = local.LanguageId,
                    LocaleKey = "Body",
                    LocaleValue = local.Body
                });

                localized.Add(new LocalizedProperty()
                {
                    LanguageId = local.LanguageId,
                    LocaleKey = "EmailAccountId",
                    LocaleValue = local.EmailAccountId.ToString()
                });

            }
            return localized;
        }
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                return RedirectToAction("List");
            
            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
				
				//Stores
				_storeMappingService.SaveStoreMappings<MessageTemplate>(messageTemplate, model.SelectedStoreIds);
                
				//locales
                UpdateLocales(messageTemplate, model);

                NotifySuccess(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                return continueEditing ? RedirectToAction("Edit", messageTemplate.Id) : RedirectToAction("List");
            }


            //If we got this far, something failed, redisplay form
            FillTokensTree(model.TokensTree, _messageTokenProvider.GetListOfAllowedTokens());
            
			//available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(ea.ToModel());
			
			//Store
			PrepareStoresMappingModel(model, messageTemplate, true);
            return View(model);
        }
        public void UpdateLocales(MessageTemplate mt, MessageTemplateModel model)
        {
            foreach (var localized in model.Locales)
            {
                int lid = localized.LanguageId;

                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment1FileId, lid, false, false), localized.Attachment1FileId, true);
                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment2FileId, lid, false, false), localized.Attachment2FileId, true);
                MediaHelper.UpdateDownloadTransientState(mt.GetLocalized(x => x.Attachment3FileId, lid, false, false), localized.Attachment3FileId, true);

                _localizedEntityService.SaveLocalizedValue(mt, x => x.BccEmailAddresses, localized.BccEmailAddresses, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Subject, localized.Subject, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Body, localized.Body, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.EmailAccountId, localized.EmailAccountId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment1FileId, localized.Attachment1FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment2FileId, localized.Attachment2FileId, lid);
                _localizedEntityService.SaveLocalizedValue(mt, x => x.Attachment3FileId, localized.Attachment3FileId, lid);
            }
        }
        public ActionResult Edit(MessageTemplateModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                messageTemplate.BccEmailAddresses = model.BccEmailAddresses;
                messageTemplate.Body = model.Body;
                messageTemplate.EmailAccountId = model.EmailAccountId;
                messageTemplate.Id = model.Id;
                messageTemplate.IsActive = model.IsActive;
                messageTemplate.Name = model.Name;
                messageTemplate.Subject = model.Subject;

                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
                //locales
                UpdateLocales(messageTemplate, model);

                return RedirectToAction("Edit", messageTemplate.Id);
            }

            //If we got this far, something failed, redisplay form
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(new EmailAccountModel
                {
                    DisplayName = ea.DisplayName,
                    Email = ea.Email,
                    EnableSsl = ea.EnableSsl,
                    Host = ea.Host,
                    Id = ea.Id,
                    Password = ea.Password,
                    Port = ea.Port,
                    UseDefaultCredentials = ea.UseDefaultCredentials,
                    Username = ea.Username
                });
            return View(model);
        }
        protected virtual void PrepareStoresMappingModel(MessageTemplateModel model, MessageTemplate messageTemplate, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            model.AvailableStores = _storeService
                .GetAllStores()
                .Select(s => s.ToModel())
                .ToList();
            if (!excludeProperties)
            {
                if (messageTemplate != null)
                {
                    model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(messageTemplate);
                }
            }
        }
 protected virtual void SaveStoreMappings(MessageTemplate messageTemplate, MessageTemplateModel model)
 {
     var existingStoreMappings = _storeMappingService.GetStoreMappings(messageTemplate);
     var allStores = _storeService.GetAllStores();
     foreach (var store in allStores)
     {
         if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.ID))
         {
             //new store
             if (existingStoreMappings.Count(sm => sm.StoreId == store.ID) == 0)
                 _storeMappingService.InsertStoreMapping(messageTemplate, store.ID);
         }
         else
         {
             //remove store
             var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.ID);
             if (storeMappingToDelete != null)
                 _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
         }
     }
 }
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");
            
            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                //attached file
                if (!model.HasAttachedDownload)
                    messageTemplate.AttachedDownloadId = 0;
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
                //Stores
                SaveStoreMappings(messageTemplate, model);
                //locales
                UpdateLocales(messageTemplate, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                
                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabIndex();

                    return RedirectToAction("Edit",  new {id = messageTemplate.ID});
                }
                return RedirectToAction("List");
            }


            //If we got this far, something failed, redisplay form
            model.HasAttachedDownload = model.AttachedDownloadId > 0;
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(ea.ToModel());
            //Store
            PrepareStoresMappingModel(model, messageTemplate, true);
            return View(model);
        }
        protected virtual void PrepareStoresMappingModel(MessageTemplateModel model, MessageTemplate messageTemplate, bool excludeProperties)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (!excludeProperties && messageTemplate != null)
                model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(messageTemplate).ToList();

            var allStores = _storeService.GetAllStores();
            foreach (var store in allStores)
            {
                model.AvailableStores.Add(new SelectListItem
                {
                    Text = store.Name,
                    Value = store.Id.ToString(),
                    Selected = model.SelectedStoreIds.Contains(store.Id)
                });
            }
        }
Ejemplo n.º 42
0
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
            {
                return(AccessDeniedView());
            }

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);

            if (messageTemplate == null)
            {
                //No message template found with the specified id
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                //attached file
                if (!model.HasAttachedDownload)
                {
                    messageTemplate.AttachedDownloadId = 0;
                }
                if (model.SendImmediately)
                {
                    messageTemplate.DelayBeforeSend = null;
                }
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);

                //activity log
                _customerActivityService.InsertActivity("EditMessageTemplate", _localizationService.GetResource("ActivityLog.EditMessageTemplate"), messageTemplate.Id);

                //Stores
                SaveStoreMappings(messageTemplate, model);
                //locales
                UpdateLocales(messageTemplate, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));

                if (continueEditing)
                {
                    return(RedirectToAction("Edit", new { id = messageTemplate.Id }));
                }
                return(RedirectToAction("List"));
            }


            //If we got this far, something failed, redisplay form
            model.HasAttachedDownload = model.AttachedDownloadId > 0;
            var allowedTokens = string.Join(", ", _messageTokenProvider.GetListOfAllowedTokens(messageTemplate.GetTokenGroups()));

            model.AllowedTokens = string.Format("{0}{1}{1}{2}{1}", allowedTokens, Environment.NewLine,
                                                _localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Tokens.ConditionalStatement"));
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
            {
                model.AvailableEmailAccounts.Add(new SelectListItem {
                    Text = ea.DisplayName, Value = ea.Id.ToString()
                });
            }
            //locales (update email account dropdownlists)
            foreach (var locale in model.Locales)
            {
                //available email accounts (we add "Standard" value for localizable field)
                locale.AvailableEmailAccounts.Add(new SelectListItem
                {
                    Text  = _localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Fields.EmailAccount.Standard"),
                    Value = "0"
                });
                foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                {
                    locale.AvailableEmailAccounts.Add(new SelectListItem
                    {
                        Text     = ea.DisplayName,
                        Value    = ea.Id.ToString(),
                        Selected = ea.Id == locale.EmailAccountId
                    });
                }
            }
            //Store
            PrepareStoresMappingModel(model, messageTemplate, true);
            return(View(model));
        }
        public ActionResult Edit(MessageTemplateModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMessageTemplates))
                return AccessDeniedView();

            var messageTemplate = _messageTemplateService.GetMessageTemplateById(model.Id);
            if (messageTemplate == null)
                //No message template found with the specified id
                return RedirectToAction("List");
            
            if (ModelState.IsValid)
            {
                messageTemplate = model.ToEntity(messageTemplate);
                //attached file
                if (!model.HasAttachedDownload)
                    messageTemplate.AttachedDownloadId = 0;
                if (model.SendImmediately)
                    messageTemplate.DelayBeforeSend = null;
                _messageTemplateService.UpdateMessageTemplate(messageTemplate);
                //Stores
                SaveStoreMappings(messageTemplate, model);
                //locales
                UpdateLocales(messageTemplate, model);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Updated"));
                
                if (continueEditing)
                {
                    return RedirectToAction("Edit",  new {id = messageTemplate.Id});
                }
                return RedirectToAction("List");
            }


            //If we got this far, something failed, redisplay form
            model.HasAttachedDownload = model.AttachedDownloadId > 0;
            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfAllowedTokens());
            //available email accounts
            foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                model.AvailableEmailAccounts.Add(new SelectListItem { Text = ea.DisplayName, Value = ea.Id.ToString() });
            //locales (update email account dropdownlists)
            foreach (var locale in model.Locales)
            {
                //available email accounts (we add "Standard" value for localizable field)
                locale.AvailableEmailAccounts.Add(new SelectListItem
                {
                    Text = _localizationService.GetResource("Admin.ContentManagement.MessageTemplates.Fields.EmailAccount.Standard"),
                    Value = "0"
                });
                foreach (var ea in _emailAccountService.GetAllEmailAccounts())
                    locale.AvailableEmailAccounts.Add(new SelectListItem
                    {
                        Text = ea.DisplayName,
                        Value = ea.Id.ToString(),
                        Selected = ea.Id == locale.EmailAccountId
                    });
            }
            //Store
            PrepareStoresMappingModel(model, messageTemplate, true);
            return View(model);
        }