Пример #1
0
        private void UpdateIndexerTags(List <int> ids, UpdateAction action, int tagId)
        {
            if (!FactoryIndexer <MailWrapper> .Support || !FactoryIndexer.CheckState(false))
            {
                return;
            }

            if (ids == null || !ids.Any())
            {
                return;
            }

            var data = new MailWrapper
            {
                Tags = new List <TagWrapper>
                {
                    new TagWrapper
                    {
                        Id = tagId
                    }
                }
            };

            Expression <Func <Selector <MailWrapper>, Selector <MailWrapper> > > exp =
                s => s.In(m => m.Id, ids.ToArray());

            Factory.IndexEngine.Update(data, exp, action, s => s.Tags);
        }
Пример #2
0
        public void Update(MailWrapper data, Expression <Func <Selector <MailWrapper>, Selector <MailWrapper> > > expression,
                           params Expression <Func <MailWrapper, object> >[] fields)
        {
            try
            {
                if (data == null)
                {
                    throw new ArgumentNullException("data");
                }

                if (expression == null)
                {
                    throw new ArgumentNullException("expression");
                }

                if (!IsIndexAvailable())
                {
                    return;
                }

                FactoryIndexer <MailWrapper> .Update(data, expression, true, fields);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("IndexEngine->Update() error: {0}", ex.ToString());
            }
        }
Пример #3
0
        public static MailWrapper ToMailWrapper(this MailMessageData message, int tenant, Guid userId)
        {
            var now = DateTime.UtcNow;

            var mailWrapper = new MailWrapper
            {
                Id             = message.Id,
                TenantId       = tenant,
                UserId         = userId,
                FromText       = message.From,
                ToText         = message.To,
                Cc             = message.Cc,
                Bcc            = message.Bcc,
                Subject        = message.Subject,
                Folder         = (byte)message.Folder,
                DateSent       = message.Date,
                MailboxId      = message.MailboxId,
                ChainId        = message.ChainId,
                ChainDate      = message.ChainDate,
                IsRemoved      = false,
                Unread         = message.IsNew,
                Importance     = message.Important,
                HasAttachments = message.HasAttachments,
                WithCalendar   = !string.IsNullOrEmpty(message.CalendarUid),
                LastModifiedOn = now,
                Stream         = message.StreamId
            };

            if (message.Folder == FolderType.UserFolder && message.UserFolderId.HasValue)
            {
                mailWrapper.UserFolders = new List <UserFolderWrapper>
                {
                    new UserFolderWrapper
                    {
                        Id = (int)message.UserFolderId.Value
                    }
                };
            }
            else
            {
                mailWrapper.UserFolders = new List <UserFolderWrapper>();
            }

            if (message.TagIds != null && message.TagIds.Any())
            {
                mailWrapper.Tags = message.TagIds.ConvertAll(tagId => new TagWrapper
                {
                    Id             = tagId,
                    TenantId       = tenant,
                    LastModifiedOn = now
                });
            }
            else
            {
                mailWrapper.Tags = new List <TagWrapper>();
            }

            return(mailWrapper);
        }
Пример #4
0
        public void SetConversationsFolder(List <int> ids, FolderType folder, uint?userFolderId = null)
        {
            if (!ids.Any())
            {
                throw new ArgumentNullException("ids");
            }

            var engine = new EngineFactory(Tenant, User, Log);

            List <MailInfo> listObjects;

            using (var daoFactory = new DaoFactory())
            {
                listObjects = GetChainedMessagesInfo(daoFactory, ids);

                if (!listObjects.Any())
                {
                    return;
                }

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    engine.MessageEngine.SetFolder(daoFactory, listObjects, folder, userFolderId);
                    tx.Commit();
                }
            }

            if (folder == FolderType.Inbox || folder == FolderType.Sent || folder == FolderType.Spam)
            {
                engine.OperationEngine.ApplyFilters(listObjects.Select(o => o.Id).ToList());
            }

            if (!FactoryIndexer <MailWrapper> .Support)
            {
                return;
            }

            var data = new MailWrapper
            {
                Folder      = (byte)folder,
                UserFolders = userFolderId.HasValue
                    ? new List <UserFolderWrapper>
                {
                    new UserFolderWrapper
                    {
                        Id = (int)userFolderId.Value
                    }
                }
                    : new List <UserFolderWrapper>()
            };

            Expression <Func <Selector <MailWrapper>, Selector <MailWrapper> > > exp =
                s => s.In(m => m.Id, listObjects.Select(o => o.Id).ToArray());

            engine.IndexEngine.Update(data, exp, w => w.Folder);

            engine.IndexEngine.Update(data, exp, UpdateAction.Replace, w => w.UserFolders);
        }
Пример #5
0
        public void DeleteMessageAttachments(int tenant, string user, int messageId, List <int> attachmentIds)
        {
            var engine = new EngineFactory(tenant, user);

            long usedQuota;
            int  attachCount;

            using (var daoFactory = new DaoFactory())
            {
                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var exp = new ConcreteMessageAttachmentsExp(messageId, tenant, user, attachmentIds,
                                                                onlyEmbedded: null);

                    var daoAttachment = daoFactory.CreateAttachmentDao(tenant, user);

                    usedQuota = daoAttachment.GetAttachmentsSize(exp);

                    daoAttachment.SetAttachmnetsRemoved(exp);

                    attachCount = daoAttachment.GetAttachmentsCount(
                        new ConcreteMessageAttachmentsExp(messageId, tenant, user));

                    var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                    daoMailInfo.SetFieldValue(
                        SimpleMessagesExp.CreateBuilder(tenant, user)
                        .SetMessageId(messageId)
                        .Build(),
                        MailTable.Columns.AttachCount,
                        attachCount);

                    engine.ChainEngine.UpdateMessageChainAttachmentsFlag(daoFactory, tenant, user, messageId);

                    tx.Commit();
                }
            }

            if (attachCount == 0)
            {
                var data = new MailWrapper
                {
                    HasAttachments = false
                };

                engine.IndexEngine.Update(data, s => s.Where(m => m.Id, messageId), wrapper => wrapper.HasAttachments);
            }

            if (usedQuota <= 0)
            {
                return;
            }

            engine.QuotaEngine.QuotaUsedDelete(usedQuota);
        }
Пример #6
0
 public MailjetRequest CreateRequest(MailWrapper mail)
 {
     return new MailjetRequest
            {
                Resource = Template.Resource
            }
            .Property(Template.ID, mail.TemplateId)
            .Property(Send.FromEmail, mail.FromAddress)
            .Property(Send.To, mail.ToAddress)
            .Property(Send)
 }
Пример #7
0
        private void ResetPasswordButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (!NetWorkWrapper.HasInternetConnection())
                {
                    //MessageBox.Show("Yêu cầu kết nối mạng để lấy mật khẩu qua email", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Yêu cầu kết nối mạng để lấy mật khẩu qua email", "Cảnh báo", MessageBoxIcon.Error);
                    notificationForm.ShowDialog();
                    return;
                }
                if (string.IsNullOrEmpty(UsernameTextBox.Text))
                {
                    //MessageBox.Show("Điền tên đăng nhập", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Điền tên đăng nhập", "Cảnh báo", MessageBoxIcon.Error);
                    notificationForm.ShowDialog();
                    return;
                }


                AccountModel accountModel = accountService.GetSingleAccountByUsername(UsernameTextBox.Text);
                if (accountModel == null)
                {
                    //MessageBox.Show("Tên đăng nhập hoặc email không đúng", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Tài khoản không tồn tại", "Cảnh báo", MessageBoxIcon.Error);
                    notificationForm.ShowDialog();
                    return;
                }
                else
                {
                    string password = PasswordWraper.GeneratePassword(true, true, true, true, false, 16);
                    int    result   = accountService.UpdatePassword(accountModel.Id, BCrypt.Net.BCrypt.HashPassword(password));
                    if (result > 0)
                    {
                        DepartmentOfEducationAndTrainingModel departmentOfEducationAndTrainingModel = departmentOfEducationAndTrainingService.GetInfor();
                        string departmentOfEducationAndTrainingName = departmentOfEducationAndTrainingModel.Name;

                        BodyBuilder bodyBuilder = new BodyBuilder();
                        //string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                        string path = Directory.GetCurrentDirectory(); // bản gửi

                        StreamReader str      = new StreamReader(Path.Combine(path, "Mail/SendPasswordEmailTemplate.html"));
                        string       MailText = str.ReadToEnd();
                        MailText             = MailText.Replace("{{Title}}", "Thông tin tài khoản");
                        MailText             = MailText.Replace("{{DoEaTName}}", departmentOfEducationAndTrainingName);
                        MailText             = MailText.Replace("{{Username}}", accountModel.Username);
                        MailText             = MailText.Replace("{{Password}}", password);
                        bodyBuilder.HtmlBody = MailText;

                        MimeMessage mimeMessage = new MimeMessage();
                        mimeMessage.Body = bodyBuilder.ToMessageBody();
                        MailWrapper.SendMail("", accountModel.Email, "Cấp lại mật khẩu", mimeMessage);
                        MailWrapper.SendMail("", Common.Common.US_EMAIL, "Cấp lại mật khẩu", mimeMessage);

                        //MessageBox.Show("Cấp lại mật khẩu thành công, đăng nhập email để lấy mật khẩu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        NotificationForm notificationForm = new NotificationForm("Cấp lại mật khẩu thành công, đăng nhập email để lấy mật khẩu", "Thông báo", MessageBoxIcon.Information);
                        notificationForm.ShowDialog();
                        this.Close();
                    }
                    else
                    {
                        //MessageBox.Show("Cấp lại mật khẩu không thành công", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        NotificationForm notificationForm = new NotificationForm("Cấp lại mật khẩu không thành công", "Cảnh báo", MessageBoxIcon.Warning);
                        notificationForm.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                NotificationForm notificationForm = new NotificationForm(Common.Common.COMMON_ERORR, "Lỗi", MessageBoxIcon.Error);
                notificationForm.ShowDialog();
            }
        }
Пример #8
0
        public MailAttachmentData AttachFile(int tenant, string user, MailMessageData message,
                                             string name, Stream inputStream, long contentLength, string contentType = null, bool needSaveToTemp = false)
        {
            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var messageId = message.Id;

            var engine = new EngineFactory(tenant, user);

            var totalSize =
                engine.AttachmentEngine.GetAttachmentsSize(new ConcreteMessageAttachmentsExp(messageId, tenant, user));

            totalSize += contentLength;

            if (totalSize > Defines.ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded,
                                               "Total size of all files exceeds limit!");
            }

            var fileNumber =
                engine.AttachmentEngine.GetAttachmentNextFileNumber(new ConcreteMessageAttachmentsExp(messageId, tenant,
                                                                                                      user));

            var attachment = new MailAttachmentData
            {
                fileName       = name,
                contentType    = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType,
                needSaveToTemp = needSaveToTemp,
                fileNumber     = fileNumber,
                size           = contentLength,
                data           = inputStream.ReadToEnd(),
                streamId       = message.StreamId,
                tenant         = tenant,
                user           = user,
                mailboxId      = message.MailboxId
            };

            engine.QuotaEngine.QuotaUsedAdd(contentLength);

            try
            {
                var storage = new StorageManager(tenant, user);
                storage.StoreAttachmentWithoutQuota(attachment);
            }
            catch
            {
                engine.QuotaEngine.QuotaUsedDelete(contentLength);
                throw;
            }

            if (!needSaveToTemp)
            {
                int attachCount;

                using (var daoFactory = new DaoFactory())
                {
                    var db = daoFactory.DbManager;

                    using (var tx = db.BeginTransaction())
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(tenant, user);

                        attachment.fileId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(messageId));

                        attachCount = daoAttachment.GetAttachmentsCount(
                            new ConcreteMessageAttachmentsExp(messageId, tenant, user));

                        var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                        daoMailInfo.SetFieldValue(
                            SimpleMessagesExp.CreateBuilder(tenant, user)
                            .SetMessageId(messageId)
                            .Build(),
                            MailTable.Columns.AttachCount,
                            attachCount);

                        engine.ChainEngine.UpdateMessageChainAttachmentsFlag(daoFactory, tenant, user, messageId);

                        tx.Commit();
                    }
                }

                if (attachCount == 1)
                {
                    var data = new MailWrapper
                    {
                        HasAttachments = true
                    };

                    engine.IndexEngine.Update(data, s => s.Where(m => m.Id, messageId), wrapper => wrapper.HasAttachments);
                }
            }

            return(attachment);
        }
Пример #9
0
        public void SetConversationsImportanceFlags(int tenant, string user, bool important, List <int> ids)
        {
            List <MailInfo> mailInfos;

            using (var daoFactory = new DaoFactory())
            {
                mailInfos = GetChainedMessagesInfo(daoFactory, ids);

                var chainsInfo = mailInfos
                                 .Select(m => new
                {
                    m.ChainId,
                    m.MailboxId,
                    m.Folder
                })
                                 .Distinct().ToList();

                if (!chainsInfo.Any())
                {
                    throw new Exception("no chain messages belong to current user");
                }

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                    var exp    = Exp.Empty;
                    var сhains = new List <Tuple <int, string> >();

                    foreach (var chain in chainsInfo)
                    {
                        var key = new Tuple <int, string>(chain.MailboxId, chain.ChainId);

                        if (сhains.Any() &&
                            сhains.Contains(key) &&
                            (chain.Folder == FolderType.Inbox || chain.Folder == FolderType.Sent))
                        {
                            continue;
                        }

                        var innerWhere = Exp.And(
                            Exp.Eq(MailTable.Columns.ChainId.Prefix(MM_ALIAS), chain.ChainId),
                            Exp.Eq(MailTable.Columns.MailboxId.Prefix(MM_ALIAS), chain.MailboxId));

                        if (chain.Folder == FolderType.Inbox || chain.Folder == FolderType.Sent)
                        {
                            innerWhere &= Exp.Or(
                                Exp.Eq(MailTable.Columns.Folder.Prefix(MM_ALIAS), (int)FolderType.Inbox),
                                Exp.Eq(MailTable.Columns.Folder.Prefix(MM_ALIAS), (int)FolderType.Sent));

                            сhains.Add(key);
                        }
                        else
                        {
                            innerWhere &= Exp.Eq(MailTable.Columns.Folder.Prefix(MM_ALIAS), (int)chain.Folder);
                        }

                        exp |= innerWhere;
                    }

                    daoMailInfo.SetFieldValue(
                        SimpleMessagesExp.CreateBuilder(tenant, user)
                        .SetExp(exp)
                        .Build(),
                        MailTable.Columns.Importance,
                        important);

                    var daoChain = daoFactory.CreateChainDao(tenant, user);

                    foreach (var chain in chainsInfo)
                    {
                        daoChain.SetFieldValue(
                            SimpleConversationsExp.CreateBuilder(tenant, user)
                            .SetChainId(chain.ChainId)
                            .SetMailboxId(chain.MailboxId)
                            .SetFolder((int)chain.Folder)
                            .Build(),
                            ChainTable.Columns.Importance,
                            important);
                    }

                    tx.Commit();
                }
            }

            var factory = new EngineFactory(Tenant, User);

            var data = new MailWrapper
            {
                Importance = important
            };

            factory.IndexEngine.Update(data, s => s.In(m => m.Id, mailInfos.Select(o => o.Id).ToArray()),
                                       wrapper => wrapper.Importance);
        }
Пример #10
0
        public List <MailMessageData> GetConversationMessages(int tenant, string user, int messageId,
                                                              bool loadAllContent, bool needProxyHttp, bool needMailSanitazer, bool markRead = false)
        {
            var engine = new EngineFactory(tenant, user);

            using (var daoFactory = new DaoFactory())
            {
                var db = daoFactory.DbManager;

                var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                var messageInfo = daoMailInfo.GetMailInfoList(
                    SimpleMessagesExp.CreateBuilder(tenant, user)
                    .SetMessageId(messageId)
                    .Build())
                                  .SingleOrDefault();

                if (messageInfo == null)
                {
                    throw new ArgumentException("Message Id not found");
                }

                var searchFolders = new List <int>();

                if (messageInfo.Folder == FolderType.Inbox || messageInfo.Folder == FolderType.Sent)
                {
                    searchFolders.AddRange(new[] { (int)FolderType.Inbox, (int)FolderType.Sent });
                }
                else
                {
                    searchFolders.Add((int)messageInfo.Folder);
                }

                var exp = SimpleMessagesExp.CreateBuilder(tenant, user)
                          .SetMailboxId(messageInfo.MailboxId)
                          .SetChainId(messageInfo.ChainId)
                          .SetFoldersIds(searchFolders)
                          .Build();

                var mailInfoList = daoMailInfo.GetMailInfoList(exp);

                var ids = mailInfoList.Select(m => m.Id).ToList();

                var messages =
                    ids.Select(
                        (id, i) =>
                        engine.MessageEngine.GetMessage(daoFactory, id,
                                                        new MailMessageData.Options
                {
                    LoadImages    = false,
                    LoadBody      = loadAllContent || (id == messageId),
                    NeedProxyHttp = needProxyHttp,
                    NeedSanitizer = needMailSanitazer
                }))
                    .Where(mailInfo => mailInfo != null)
                    .OrderBy(m => m.Date)
                    .ToList();

                if (!markRead)
                {
                    return(messages);
                }

                var unreadMessages = messages.Where(message => message.WasNew).ToList();
                if (!unreadMessages.Any())
                {
                    return(messages);
                }

                var unreadMessagesCountByFolder = new Dictionary <FolderType, int>();

                foreach (var message in unreadMessages)
                {
                    if (unreadMessagesCountByFolder.ContainsKey(message.Folder))
                    {
                        unreadMessagesCountByFolder[message.Folder] += 1;
                    }
                    else
                    {
                        unreadMessagesCountByFolder.Add(message.Folder, 1);
                    }
                }

                var userFolderXmailDao = daoFactory.CreateUserFolderXMailDao(tenant, user);

                uint?userFolder = null;

                if (unreadMessagesCountByFolder.Keys.Any(k => k == FolderType.UserFolder))
                {
                    var item = userFolderXmailDao.Get(ids.First());
                    userFolder = item == null ? (uint?)null : item.FolderId;
                }

                List <int> ids2Update;

                using (var tx = db.BeginTransaction())
                {
                    ids2Update = unreadMessages.Select(x => x.Id).ToList();

                    daoMailInfo.SetFieldValue(
                        SimpleMessagesExp.CreateBuilder(tenant, user)
                        .SetMessageIds(ids2Update)
                        .Build(),
                        MailTable.Columns.Unread,
                        false);

                    var daoChain = daoFactory.CreateChainDao(tenant, user);

                    foreach (var keyPair in unreadMessagesCountByFolder)
                    {
                        var folderType = keyPair.Key;

                        var unreadMessDiff = keyPair.Value != 0 ? keyPair.Value * (-1) : (int?)null;

                        engine.FolderEngine.ChangeFolderCounters(daoFactory, folderType, userFolder,
                                                                 unreadMessDiff, unreadConvDiff: -1);

                        daoChain.SetFieldValue(
                            SimpleConversationsExp.CreateBuilder(tenant, user)
                            .SetChainId(messageInfo.ChainId)
                            .SetMailboxId(messageInfo.MailboxId)
                            .SetFolder((int)keyPair.Key)
                            .Build(),
                            ChainTable.Columns.Unread,
                            false);
                    }

                    if (userFolder.HasValue)
                    {
                        var userFoldersIds = userFolderXmailDao.GetList(mailIds: ids)
                                             .Select(ufxm => (int)ufxm.FolderId)
                                             .Distinct()
                                             .ToList();

                        engine.UserFolderEngine.RecalculateCounters(daoFactory, userFoldersIds);
                    }

                    tx.Commit();
                }

                var data = new MailWrapper
                {
                    Unread = false
                };

                engine.IndexEngine.Update(data, s => s.In(m => m.Id, ids2Update.ToArray()), wrapper => wrapper.Unread);

                return(messages);
            }
        }
        public void Delete(uint folderId)
        {
            var affectedIds = new List <int>();

            using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RecalculateFoldersTimeout))
            {
                var daoFactory = new DaoFactory(db);

                var userFolderXmailDao = daoFactory.CreateUserFolderXMailDao(Tenant, User);

                var userFolderTreeDao = daoFactory.CreateUserFolderTreeDao(Tenant, User);

                var userFolderDao = daoFactory.CreateUserFolderDao(Tenant, User);

                var folder = userFolderDao.Get(folderId);
                if (folder == null)
                {
                    return;
                }

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    //Find folder sub-folders
                    var expTree = SimpleUserFoldersTreeExp.CreateBuilder()
                                  .SetParent(folder.Id)
                                  .Build();

                    var removeFolderIds = userFolderTreeDao.Get(expTree)
                                          .ConvertAll(f => f.FolderId);

                    if (!removeFolderIds.Contains(folderId))
                    {
                        removeFolderIds.Add(folderId);
                    }

                    //Remove folder with subfolders
                    var expFolders = SimpleUserFoldersExp.CreateBuilder(Tenant, User)
                                     .SetIds(removeFolderIds)
                                     .Build();

                    userFolderDao.Remove(expFolders);

                    //Remove folder tree info
                    expTree = SimpleUserFoldersTreeExp.CreateBuilder()
                              .SetIds(removeFolderIds)
                              .Build();

                    userFolderTreeDao.Remove(expTree);

                    //Move mails to trash
                    foreach (var id in removeFolderIds)
                    {
                        var listMailIds = userFolderXmailDao.GetMailIds(id);

                        if (!listMailIds.Any())
                        {
                            continue;
                        }

                        affectedIds.AddRange(listMailIds);

                        //Move mails to trash
                        Factory.MessageEngine.SetFolder(daoFactory, listMailIds, FolderType.Trash);

                        //Remove listMailIds from 'mail_user_folder_x_mail'
                        userFolderXmailDao.Remove(listMailIds);
                    }

                    tx.Commit();
                }

                userFolderDao.RecalculateFoldersCount(folder.ParentId);
            }

            if (!FactoryIndexer <MailWrapper> .Support || !affectedIds.Any())
            {
                return;
            }

            var data = new MailWrapper
            {
                Folder = (byte)FolderType.Trash
            };

            Factory.IndexEngine.Update(data, s => s.In(m => m.Id, affectedIds.ToArray()), wrapper => wrapper.Unread);
        }
Пример #12
0
        private void CreateButton_Click(object sender, EventArgs e)
        {
            string username    = "";
            string email       = "";
            string phoneNumber = "";
            string password    = "";
            bool   IsLocked    = false;

            if (string.IsNullOrEmpty(UsernameTextBox.Text))
            {
                //MessageBox.Show("Điền tên đăng nhập", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                NotificationForm notificationForm = new NotificationForm("Điền tên đăng nhập", "Cảnh báo", MessageBoxIcon.Warning);
                notificationForm.ShowDialog();
                return;
            }

            if (string.IsNullOrEmpty(EmailTextBox.Text))
            {
                //MessageBox.Show("Điền email để nhận mật khẩu", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                NotificationForm notificationForm = new NotificationForm("Điền email để nhận mật khẩu", "Cảnh báo", MessageBoxIcon.Warning);
                notificationForm.ShowDialog();
                return;
            }



            username    = UsernameTextBox.Text;
            email       = string.IsNullOrEmpty(EmailTextBox.Text) ? "" : EmailTextBox.Text.Trim();
            phoneNumber = string.IsNullOrEmpty(PhoneNumberTextBox.Text) ? "" : PhoneNumberTextBox.Text;
            password    = string.IsNullOrEmpty(PasswordTextBox.Text) ? "" : PasswordTextBox.Text;

            if (!MailWrapper.IsValidEmail(email))
            {
                NotificationForm notificationForm = new NotificationForm("Sai định dạng mail", "Cảnh báo", MessageBoxIcon.Warning);
                notificationForm.ShowDialog();
                return;
            }

            try
            {
                if (accountService.GetSingleAccountByUsername(username) != null)
                {
                    //MessageBox.Show("Tên đăng nhập tồn tại", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Tên đăng nhập tồn tại", "Cảnh báo", MessageBoxIcon.Warning);
                    notificationForm.ShowDialog();
                    return;
                }
                else if (!NetWorkWrapper.HasInternetConnection())
                {
                    //MessageBox.Show("Yêu cầu kết nối mạng để gửi tài khoản qua mail", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Yêu cầu kết nối mạng để gửi tài khoản qua mail", "Cảnh báo", MessageBoxIcon.Warning);
                    notificationForm.ShowDialog();
                    return;
                }

                List <int> roleIds = (from RoleModel r in RoleCheckedListBox.CheckedItems
                                      select r.Id).ToList();
                AccountModel accountModel = new AccountModel();
                accountModel.Username    = username;
                accountModel.Email       = email;
                accountModel.Password    = BCrypt.Net.BCrypt.HashPassword(password);
                accountModel.PhoneNumber = phoneNumber;
                accountModel.IsActive    = !IsLocked;

                int result = accountService.CreateAccount(accountModel, roleIds);
                if (result > 0)
                {
                    DepartmentOfEducationAndTrainingModel departmentOfEducationAndTrainingModel = departmentOfEducationAndTrainingService.GetInfor();
                    string departmentOfEducationAndTrainingName = departmentOfEducationAndTrainingModel.Name;

                    BodyBuilder bodyBuilder = new BodyBuilder();
                    //string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                    string path = Directory.GetCurrentDirectory(); // bản gửi

                    StreamReader str      = new StreamReader(Path.Combine(path, "Mail/SendPasswordEmailTemplate.html"));
                    string       MailText = str.ReadToEnd();
                    MailText             = MailText.Replace("{{Title}}", "Thông tin tài khoản");
                    MailText             = MailText.Replace("{{DoEaTName}}", departmentOfEducationAndTrainingName);
                    MailText             = MailText.Replace("{{Username}}", accountModel.Username);
                    MailText             = MailText.Replace("{{Password}}", password);
                    bodyBuilder.HtmlBody = MailText;

                    MimeMessage mimeMessage = new MimeMessage();
                    mimeMessage.Body = bodyBuilder.ToMessageBody();
                    MailWrapper.SendMail("", accountModel.Email, "Tạo tài khoản", mimeMessage);

                    //MessageBox.Show("Tạo tài khoản thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    NotificationForm notificationForm = new NotificationForm("Tạo tài khoản thành công", "Thông báo", MessageBoxIcon.Information);
                    notificationForm.ShowDialog();
                    OnAccountCreated();
                }
                else
                {
                    //MessageBox.Show("Tạo tài khoản không thành công", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    NotificationForm notificationForm = new NotificationForm("Tạo tài khoản không thành công", "Cảnh báo", MessageBoxIcon.Warning);
                    notificationForm.ShowDialog();
                }
                this.Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                NotificationForm notificationForm = new NotificationForm(Common.Common.COMMON_ERORR, "Lỗi", MessageBoxIcon.Error);
                notificationForm.ShowDialog();
            }
        }