Пример #1
0
        public bool DoSendEmail(string to, string subject, string body, string username, bool useEmailTemplate, EmailAccountType emailUserType, bool fromCache)
        {
            bool   sendSuccess      = false;
            string smtpEmailAddress = null;

            //if (emailUserType == EmailUserType.Default && to.ToUpper().EndsWith("@QQ.COM"))
            //{
            //    //useBackupEmail = !useBackupEmail;//如果是qq邮箱,则切换
            //    emailUserType = EmailUserType._163;
            //}

            //if (emailUserType == EmailUserType.Default)
            //{
            //    emailUserType = EmailUserType.KJH8;//默认使用KJH8发送
            //}

            try
            {
                body = this.GetEmailTemplate(body, useEmailTemplate);

                EmailUser targetEmailUser = this.GetEmailUser(emailUserType);
                smtpEmailAddress = targetEmailUser.EmailAddress;

                MailMessage m_message = new MailMessage();
                m_message.From = new MailAddress(targetEmailUser.EmailAddress, targetEmailUser.DisplayName);
                m_message.To.Add(new MailAddress(to));
                m_message.Subject    = subject;
                m_message.IsBodyHtml = true;//允许使用html格式
                m_message.Body       = body;

                SmtpClient m_smtpClient = new SmtpClient();
                m_smtpClient.Host = targetEmailUser.SmtpHost;
                m_smtpClient.Port = targetEmailUser.SmtpPort;
                if (targetEmailUser.NeedCredentials)
                {
                    m_smtpClient.Credentials = new System.Net.NetworkCredential(targetEmailUser.EmailAddress, targetEmailUser.Password);
                }

                m_smtpClient.Send(m_message);

                sendSuccess = true;
            }
            catch (Exception e)
            {
                LogUtility.EmailLogger.ErrorFormat($"TO:{to},Subject:{subject},Username:{username},Message:{e.Message}", e);
                sendSuccess = false;
            }
            finally
            {
                string cacheUsed = fromCache ? "缓存" : "直接发送";
                if (sendSuccess)
                {
                    //记录到AutoSendEmail中进行备份
                    XmlDataContext   xmlCtx   = new XmlDataContext();
                    AutoSendEmailBak emailBak = new AutoSendEmailBak()
                    {
                        Address  = to,
                        Body     = body,
                        Subject  = subject,
                        SendTime = DateTime.Now,
                        UserName = username
                    };
                    xmlCtx.Insert(emailBak);

                    LogUtility.EmailLogger.Info($"发送Email成功({cacheUsed})。To:{to},Subject:{subject},UserName:{username}。by:{smtpEmailAddress}");
                }
                else
                {
                    LogUtility.EmailLogger.Error($"发送Email失败({cacheUsed})。To:{to},Subject:{subject},UserName:{username}。by:{smtpEmailAddress}");
                }
            }
            return(sendSuccess);
        }
Пример #2
0
        public void UpdateMyPassword(UpdatePasswordModel model)
        {
            IValidator validator = new FluentValidator <UpdatePasswordModel, UpdatePasswordModelValidationRules>(model);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var identity = (CustomIdentity)Thread.CurrentPrincipal?.Identity;
            var user     = _repositoryUser
                           .Join(x => x.Language)
                           .Join(x => x.Person)
                           .FirstOrDefault(e => e.Id == identity.UserId);

            if (user == null)
            {
                throw new NotFoundException();
            }

            if (model.OldPassword.ToSha512() != user.Password)
            {
                throw new NotFoundException(Messages.DangerIncorrectOldPassword);
            }

            var userHistory = user.CreateMapped <User, UserHistory>();

            userHistory.Id          = GuidHelper.NewGuid();
            userHistory.ReferenceId = user.Id;
            userHistory.CreatorId   = user.Creator.Id;

            userHistory.PersonId   = user.Person.Id;
            userHistory.LanguageId = user.Language.Id;


            _repositoryUserHistory.Add(userHistory, true);


            var password = model.Password;

            user.Password             = password.ToSha512();
            user.LastModificationTime = DateTime.Now;
            user.LastModifier         = user;
            var version = user.Version;

            user.Version = version + 1;
            var affectedUser = _repositoryUser.Update(user, true);

            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserPassword)
            {
                return;
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_serviceMain, _smtp);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.UpdateMyPassword);
        }
Пример #3
0
        public void UpdateMyInformation(UpdateInformationModel model)
        {
            IValidator validator = new FluentValidator <UpdateInformationModel, UpdateInformationModelValidationRules>(model);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }


            var language = _repositoryLanguage.Get(e => e.Id == model.Language.Id);

            if (language == null)
            {
                throw new ParentNotFoundException();
            }


            var identity = (CustomIdentity)Thread.CurrentPrincipal?.Identity;
            var user     = _repositoryUser
                           .Join(x => x.Creator)
                           .Join(x => x.Language)
                           .Join(x => x.Person)
                           .FirstOrDefault(e => e.Id == identity.UserId);

            if (user == null)
            {
                throw new NotFoundException();
            }


            var person = user.Person;

            if (model.Username != user.Username)
            {
                if (_repositoryUser.Get().Any(p => p.Username == model.Username))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
                }
            }
            if (model.Email != user.Email)
            {
                if (_repositoryUser.Get().Any(p => p.Email == model.Email))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
                }
            }


            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id          = GuidHelper.NewGuid();
            personHistory.ReferenceId = user.Id;
            personHistory.CreatorId   = user.Creator.Id;
            _repositoryPersonHistory.Add(personHistory, true);

            person.FirstName = model.FirstName;
            person.LastName  = model.LastName;


            person.LastModificationTime = DateTime.Now;
            person.LastModifierId       = user.Id;
            var versionPerson = person.Version;

            person.Version = versionPerson + 1;
            _repositoryPerson.Update(person, true);

            var userHistory = user.CreateMapped <User, UserHistory>();

            userHistory.Id          = GuidHelper.NewGuid();
            userHistory.ReferenceId = user.Id;
            userHistory.CreatorId   = user.Creator.Id;
            userHistory.PersonId    = user.Person.Id;
            userHistory.LanguageId  = user.Language.Id;



            _repositoryUserHistory.Add(userHistory, true);

            user.Username = model.Username;
            user.Email    = model.Email;


            user.LastModificationTime = DateTime.Now;
            user.LastModifier         = user;
            user.Language             = language;

            var versionUser = user.Version;

            user.Version = versionUser + 1;

            var affectedUser = _repositoryUser.Update(user, true);

            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserInformation)
            {
                return;
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = string.Empty,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_serviceMain, _smtp);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.UpdateMyInformation);
        }
Пример #4
0
        public AddModel <UserModel> Add(AddModel <UserModel> addModel)
        {
            var validator = new FluentValidator <UserModel, UserValidationRules>(addModel.Item);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var language = _serviceMain.DefaultLanguage;


            var item = addModel.Item.CreateMapped <UserModel, User>();

            if (_repositoryUser.Get().FirstOrDefault(e => e.Username == item.Username) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
            }

            if (_repositoryUser.Get(e => e.Email == item.Email) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
            }

            var password = addModel.Item.Password.ToSha512();

            Person person;

            var maxDisplayOrderPerson = _repositoryPerson.Get().Max(e => e.DisplayOrder);
            var maxDisplayOrderUser   = _repositoryUser.Get().Max(e => e.DisplayOrder);

            if (addModel.Item.IdentityCode != null)
            {
                if (_repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode) != null)
                {
                    person = _repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode);
                }
                else
                {
                    person = new Person
                    {
                        Id                   = GuidHelper.NewGuid(),
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        DisplayOrder         = maxDisplayOrderPerson + 1,
                        Version              = 1,
                        IsApproved           = false,
                        IdentityCode         = addModel.Item.IdentityCode.Trim().Length > 0 ? addModel.Item.IdentityCode : GuidHelper.NewGuid().ToString(),
                        FirstName            = addModel.Item.FirstName,
                        LastName             = addModel.Item.LastName,
                    };
                }
            }

            else
            {
                person = new Person
                {
                    Id                   = GuidHelper.NewGuid(),
                    CreationTime         = DateTime.Now,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = maxDisplayOrderPerson + 1,
                    Version              = 1,
                    IsApproved           = false,
                    IdentityCode         = GuidHelper.NewGuid().ToString(),
                    FirstName            = addModel.Item.FirstName,
                    LastName             = addModel.Item.LastName,
                };
            }


            person.CreatorId      = _serviceMain.IdentityUser.Id;
            person.LastModifierId = _serviceMain.IdentityUser.Id;

            _repositoryPerson.Add(person, true);
            item.Id           = GuidHelper.NewGuid();
            item.Creator      = _serviceMain.IdentityUser;
            item.CreationTime = DateTime.Now;

            item.LastModificationTime = DateTime.Now;
            item.LastModifier         = _serviceMain.IdentityUser;

            item.DisplayOrder = maxDisplayOrderUser + 1;
            item.Person       = person;
            item.Language     = language;
            item.Version      = 1;

            var affectedUser = _repositoryUser.Add(item, true);

            var role = _repositoryRole.Get(x => x.Code == RoleConstants.Default.Item1);

            if (role == null)
            {
                throw new NotFoundException();
            }

            _repositoryRoleUserLine.Add(new RoleUserLine
            {
                Id                   = GuidHelper.NewGuid(),
                User                 = affectedUser,
                Role                 = role,
                Creator              = _serviceMain.IdentityUser,
                CreationTime         = DateTime.Now,
                DisplayOrder         = 1,
                LastModifier         = _serviceMain.IdentityUser,
                LastModificationTime = DateTime.Now,
                Version              = 1
            }, true);

            addModel.Item = affectedUser.CreateMapped <User, UserModel>();

            addModel.Item.Creator      = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);
            addModel.Item.LastModifier = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);
            addModel.Item.Language     = new IdName(affectedUser.Language.Id, affectedUser.Language.Name);

            addModel.Item.IdentityCode = affectedUser.Person.IdentityCode;
            addModel.Item.FirstName    = affectedUser.Person.FirstName;
            addModel.Item.LastName     = affectedUser.Person.LastName;

            if (!_serviceMain.ApplicationSettings.SendMailAfterAddUser)
            {
                return(addModel);
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_serviceMain, _smtp);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Add);
            return(addModel);
        }
Пример #5
0
        public UpdateModel <UserModel> Update(UpdateModel <UserModel> updateModel)
        {
            IValidator validator = new FluentValidator <UserModel, UserValidationRules>(updateModel.Item);

            var validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var language = _repositoryLanguage.Get(e => e.Id == updateModel.Item.Language.Id);

            if (language == null)
            {
                throw new ParentNotFoundException();
            }

            var identityUserMinRoleLevel = _serviceMain.IdentityUserMinRoleLevel;


            var itemUser = _repositoryUser

                           .Join(x => x.Person)
                           .Join(x => x.Language)
                           .Join(x => x.Creator.Person)
                           .Join(x => x.LastModifier.Person)
                           .FirstOrDefault(x => x.Id == updateModel.Item.Id && x.RoleUserLines.All(t => t.Role.Level > identityUserMinRoleLevel));

            if (itemUser == null)
            {
                throw new NotFoundException();
            }

            var person = itemUser.Person;

            if (person == null)
            {
                throw new ParentNotFoundException();
            }
            if (updateModel.Item.Username != itemUser.Username)
            {
                if (_repositoryUser.Get().Any(p => p.Username == updateModel.Item.Username))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
                }
            }

            if (updateModel.Item.Email != itemUser.Email)
            {
                if (_repositoryUser.Get().Any(p => p.Email == updateModel.Item.Email))
                {
                    throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
                }
            }


            var versionUser   = itemUser.Version;
            var versionPerson = person.Version;


            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id           = GuidHelper.NewGuid();
            personHistory.ReferenceId  = person.Id;
            personHistory.CreatorId    = _serviceMain.IdentityUser.Id;
            personHistory.CreationTime = DateTime.Now;
            _repositoryPersonHistory.Add(personHistory, true);

            person.FirstName = updateModel.Item.FirstName;
            person.LastName  = updateModel.Item.LastName;

            person.LastModificationTime = DateTime.Now;
            person.LastModifierId       = _serviceMain.IdentityUser.Id;
            person.Version = versionPerson + 1;
            var affectedPerson = _repositoryPerson.Update(person, true);


            var userHistory = itemUser.CreateMapped <User, UserHistory>();

            userHistory.Id           = GuidHelper.NewGuid();
            userHistory.ReferenceId  = itemUser.Id;
            userHistory.PersonId     = affectedPerson.Id;
            userHistory.LanguageId   = language.Id;
            userHistory.CreatorId    = _serviceMain.IdentityUser.Id;
            userHistory.CreationTime = DateTime.Now;
            _repositoryUserHistory.Add(userHistory, true);

            itemUser.Username             = updateModel.Item.Username;
            itemUser.Email                = updateModel.Item.Email;
            itemUser.IsApproved           = updateModel.Item.IsApproved;
            itemUser.Language             = language;
            itemUser.Person               = affectedPerson;
            itemUser.LastModificationTime = DateTime.Now;
            itemUser.LastModifier         = _serviceMain.IdentityUser;
            itemUser.Version              = versionUser + 1;

            var affectedUser = _repositoryUser.Update(itemUser, true);

            foreach (var line in _repositoryRoleUserLine

                     .Join(x => x.Role)
                     .Join(x => x.User)
                     .Where(x => x.User.Id == affectedUser.Id).ToList())
            {
                var lineHistory = line.CreateMapped <RoleUserLine, RoleUserLineHistory>();
                lineHistory.Id           = GuidHelper.NewGuid();
                lineHistory.ReferenceId  = line.Id;
                lineHistory.RoleId       = line.Role.Id;
                lineHistory.UserId       = line.User.Id;
                lineHistory.CreationTime = DateTime.Now;
                lineHistory.CreatorId    = _serviceMain.IdentityUser.Id;
                _repositoryRoleUserLineHistory.Add(lineHistory, true);
                _repositoryRoleUserLine.Delete(line, true);
            }

            foreach (var idCodeNameSelected in updateModel.Item.Roles)
            {
                var itemRole = _repositoryRole.Get(x => x.Id == idCodeNameSelected.Id);

                var affectedLine = _repositoryRoleUserLine.Add(new RoleUserLine
                {
                    Id                   = GuidHelper.NewGuid(),
                    User                 = affectedUser,
                    Role                 = itemRole,
                    Creator              = _serviceMain.IdentityUser,
                    CreationTime         = DateTime.Now,
                    DisplayOrder         = 1,
                    LastModifier         = _serviceMain.IdentityUser,
                    LastModificationTime = DateTime.Now,
                    Version              = 1
                }, true);

                var lineHistory = affectedLine.CreateMapped <RoleUserLine, RoleUserLineHistory>();
                lineHistory.Id          = GuidHelper.NewGuid();
                lineHistory.ReferenceId = affectedLine.Id;
                lineHistory.RoleId      = affectedLine.Role.Id;
                lineHistory.UserId      = affectedLine.User.Id;
                lineHistory.CreatorId   = affectedLine.Creator.Id;

                _repositoryRoleUserLineHistory.Add(lineHistory, true);
            }

            updateModel.Item = affectedUser.CreateMapped <User, UserModel>();

            updateModel.Item.Creator      = new IdName(itemUser.Creator.Id, itemUser.Creator.Person.DisplayName);
            updateModel.Item.LastModifier = new IdName(_serviceMain.IdentityUser.Id, _serviceMain.IdentityUser.Person.DisplayName);
            updateModel.Item.Language     = new IdName(affectedUser.Language.Id, affectedUser.Language.Name);

            updateModel.Item.IdentityCode = itemUser.Person.IdentityCode;
            updateModel.Item.FirstName    = itemUser.Person.FirstName;
            updateModel.Item.LastName     = itemUser.Person.LastName;

            if (!_serviceMain.ApplicationSettings.SendMailAfterUpdateUserInformation)
            {
                return(updateModel);
            }
            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = string.Empty,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_serviceMain, _smtp);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Update);
            return(updateModel);
        }
Пример #6
0
        public AddModel <UserModel> Add(AddModel <UserModel> addModel)
        {
            IValidator validator         = new FluentValidator <UserModel, UserValidationRules>(addModel.Item);
            var        validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var item = addModel.Item.CreateMapped <UserModel, User>();

            if (_repositoryUser.Get(e => e.Username == item.Username) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Username));
            }

            if (_repositoryUser.Get(e => e.Email == item.Email) != null)
            {
                throw new DuplicateException(string.Format(Messages.DangerFieldDuplicated, Dictionary.Email));
            }

            if (addModel.Item.BirthDate == DateTime.MinValue)
            {
                addModel.Item.BirthDate = DateTime.Now;
            }

            var password = addModel.Item.Password.ToSha512();

            // kişi bilgisi veritabanında var mı?
            // Kişi bilgisi yoksa yeni kişi bilgisi oluşturuluyor
            Person person;

            var maxDisplayOrderPerson = _repositoryPerson.Get().Max(e => e.DisplayOrder);
            var maxDisplayOrderUser   = _repositoryUser.Get().Max(e => e.DisplayOrder);

            if (addModel.Item.IdentityCode != null)
            {
                if (_repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode) != null)
                {
                    person = _repositoryPerson.Get(x => x.IdentityCode == addModel.Item.IdentityCode);
                }
                else
                {
                    person = new Person
                    {
                        Id                   = GuidHelper.NewGuid(),
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now,
                        DisplayOrder         = maxDisplayOrderPerson + 1,
                        Version              = 1,
                        IsApproved           = false,
                        IdentityCode         = addModel.Item.IdentityCode.Trim().Length > 0 ? addModel.Item.IdentityCode : GuidHelper.NewGuid().ToString(),
                        FirstName            = addModel.Item.FirstName,
                        LastName             = addModel.Item.LastName,
                        Biography            = addModel.Item.Biography,
                        BirthDate            = addModel.Item.BirthDate
                    };
                }
            }

            else
            {
                person = new Person
                {
                    Id                   = GuidHelper.NewGuid(),
                    CreationTime         = DateTime.Now,
                    LastModificationTime = DateTime.Now,
                    DisplayOrder         = maxDisplayOrderPerson + 1,
                    Version              = 1,
                    IsApproved           = false,
                    IdentityCode         = GuidHelper.NewGuid().ToString(),
                    FirstName            = addModel.Item.FirstName,
                    LastName             = addModel.Item.LastName,
                    BirthDate            = addModel.Item.BirthDate,
                    Biography            = addModel.Item.Biography
                };
            }



            person.CreatorId      = IdentityUser.Id;
            person.LastModifierId = IdentityUser.Id;

            _repositoryPerson.Add(person, true);
            item.Id           = GuidHelper.NewGuid();
            item.Creator      = IdentityUser;
            item.CreationTime = DateTime.Now;

            item.LastModificationTime = DateTime.Now;
            item.LastModifier         = IdentityUser;
            item.DisplayOrder         = maxDisplayOrderUser + 1;
            item.Person  = person;
            item.Version = 1;

            var affectedUser = _repositoryUser.Add(item, true);

            var personHistory = person.CreateMapped <Person, PersonHistory>();

            personHistory.Id             = GuidHelper.NewGuid();
            personHistory.ReferenceId    = person.Id;
            personHistory.IsDeleted      = false;
            personHistory.RestoreVersion = 0;
            _repositoryPersonHistory.Add(personHistory, true);

            var userHistory = affectedUser.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = affectedUser.Id;
            userHistory.PersonId       = affectedUser.Person.Id;
            userHistory.CreatorId      = IdentityUser.Id;
            userHistory.IsDeleted      = false;
            userHistory.RestoreVersion = 0;

            _repositoryUserHistory.Add(userHistory, true);

            var role = _repositoryRole.Get(x => x.Code == "DEFAULTROLE");

            if (role == null)
            {
                throw new NotFoundException(Messages.DangerRecordNotFound);
            }

            var affectedRoleUserLine = _repositoryRoleUserLine.Add(new RoleUserLine
            {
                Id                   = GuidHelper.NewGuid(),
                User                 = affectedUser,
                Role                 = role,
                Creator              = IdentityUser,
                CreationTime         = DateTime.Now,
                DisplayOrder         = 1,
                LastModifier         = IdentityUser,
                LastModificationTime = DateTime.Now,
                Version              = 1
            }, true);

            var roleUserLineHistory = affectedRoleUserLine.CreateMapped <RoleUserLine, RoleUserLineHistory>();

            roleUserLineHistory.Id          = GuidHelper.NewGuid();
            roleUserLineHistory.ReferenceId = roleUserLineHistory.Id;
            roleUserLineHistory.RoleId      = affectedRoleUserLine.Role.Id;
            roleUserLineHistory.UserId      = affectedRoleUserLine.User.Id;
            roleUserLineHistory.CreatorId   = affectedRoleUserLine.Creator.Id;

            _repositoryRoleUserLineHistory.Add(roleUserLineHistory, true);

            addModel.Item.Creator      = new IdCodeName(IdentityUser.Id, IdentityUser.Username, IdentityUser.Person.DisplayName);
            addModel.Item.LastModifier = new IdCodeName(IdentityUser.Id, IdentityUser.Username, IdentityUser.Person.DisplayName);


            addModel.Item.BirthDate    = affectedUser.Person.BirthDate;
            addModel.Item.IdentityCode = affectedUser.Person.IdentityCode;
            addModel.Item.FirstName    = affectedUser.Person.FirstName;
            addModel.Item.LastName     = affectedUser.Person.LastName;
            addModel.Item.Biography    = affectedUser.Person.Biography;

            if (!_serviceMain.ApplicationSettings.SendMailAfterAddUser)
            {
                return(addModel);
            }

            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = password,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = affectedUser.Person.FirstName,
                LastName     = affectedUser.Person.LastName
            };
            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.Add);
            return(addModel);
        }
        void ReleaseDesignerOutlets()
        {
            if (AddSeekiosButton != null)
            {
                AddSeekiosButton.Dispose();
                AddSeekiosButton = null;
            }

            if (AddSeekiosLabel != null)
            {
                AddSeekiosLabel.Dispose();
                AddSeekiosLabel = null;
            }

            if (AllSeekiosMapLabel != null)
            {
                AllSeekiosMapLabel.Dispose();
                AllSeekiosMapLabel = null;
            }

            if (CreditsLabel != null)
            {
                CreditsLabel.Dispose();
                CreditsLabel = null;
            }

            if (CreditsTitleLabel != null)
            {
                CreditsTitleLabel.Dispose();
                CreditsTitleLabel = null;
            }

            if (EmailUser != null)
            {
                EmailUser.Dispose();
                EmailUser = null;
            }

            if (FeedbackButton != null)
            {
                FeedbackButton.Dispose();
                FeedbackButton = null;
            }

            if (FeedbackLabel != null)
            {
                FeedbackLabel.Dispose();
                FeedbackLabel = null;
            }

            if (Head2View != null)
            {
                Head2View.Dispose();
                Head2View = null;
            }

            if (HeadView != null)
            {
                HeadView.Dispose();
                HeadView = null;
            }

            if (HistoriqueConsommationButton != null)
            {
                HistoriqueConsommationButton.Dispose();
                HistoriqueConsommationButton = null;
            }

            if (MapButton != null)
            {
                MapButton.Dispose();
                MapButton = null;
            }

            if (MyConsoLabel != null)
            {
                MyConsoLabel.Dispose();
                MyConsoLabel = null;
            }

            if (NameUser != null)
            {
                NameUser.Dispose();
                NameUser = null;
            }

            if (ParameterButton != null)
            {
                ParameterButton.Dispose();
                ParameterButton = null;
            }

            if (ParametersLabel != null)
            {
                ParametersLabel.Dispose();
                ParametersLabel = null;
            }

            if (SeekiosTutorialButton != null)
            {
                SeekiosTutorialButton.Dispose();
                SeekiosTutorialButton = null;
            }

            if (SettingsImageView != null)
            {
                SettingsImageView.Dispose();
                SettingsImageView = null;
            }

            if (UserGuideLabel != null)
            {
                UserGuideLabel.Dispose();
                UserGuideLabel = null;
            }

            if (UserImageView != null)
            {
                UserImageView.Dispose();
                UserImageView = null;
            }
        }
Пример #8
0
        public void SendEmailToUser(EmailUser user, EmailTypeOption emailTypes)
        {
            var projectRootPath = AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin", StringComparison.Ordinal));


            var templateFolderPath = Path.Combine(projectRootPath, _serviceMain.ApplicationSettings.EmailTemplatePath);
            var templateFilePath   = Path.Combine(templateFolderPath, emailTypes + ".html");
            var templateText       = FileHelper.ReadAllLines(templateFilePath);

            var from = new EmailAddress
            {
                DisplayName = _serviceMain.ApplicationSettings.SmtpSenderName,
                Address     = _serviceMain.ApplicationSettings.SmtpSenderMail
            };

            string eMailSubject;

            var emailRow = new EmailRow();

            var emailKeys = new List <EmailKey>
            {
                new EmailKey
                {
                    Key   = EmailKeyOption.ApplicationName,
                    Value = Dictionary.ApplicationName
                },
                new EmailKey
                {
                    Key   = EmailKeyOption.ApplicationUrl,
                    Value = _serviceMain.ApplicationSettings.ApplicationUrl
                },
                new EmailKey
                {
                    Key   = EmailKeyOption.FirstName,
                    Value = user.FirstName
                }
                ,
                new EmailKey
                {
                    Key   = EmailKeyOption.LastName,
                    Value = user.LastName
                }
            };

            switch (emailTypes)
            {
            case EmailTypeOption.Add:
            {
                eMailSubject = Dictionary.UserInformation;
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Username,
                        Value = user.Username
                    });
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Password,
                        Value = user.Password
                    });
                break;
            }

            case EmailTypeOption.SignUp:
            {
                eMailSubject = Dictionary.UserInformation;
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Username,
                        Value = user.Username
                    });
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Password,
                        Value = user.Password
                    });
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.ActivationCode,
                        Value = (user.Id + "@" + user.CreationTime).Encrypt()
                    });
                break;
            }

            case EmailTypeOption.ForgotPassword:
            {
                eMailSubject = Dictionary.NewPassword;

                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Username,
                        Value = user.Username
                    });
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Password,
                        Value = user.Password
                    });
                break;
            }

            case EmailTypeOption.Update:
            {
                eMailSubject = Dictionary.UserInformation;
                break;
            }

            case EmailTypeOption.UpdateMyPassword:
            {
                eMailSubject = Dictionary.NewPassword;
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Username,
                        Value = user.Username
                    });
                emailKeys.Add(new EmailKey
                    {
                        Key   = EmailKeyOption.Password,
                        Value = user.Password
                    });
                break;
            }

            case EmailTypeOption.UpdateMyInformation:
            {
                eMailSubject = Dictionary.UserInformation;
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(emailTypes), emailTypes, null);
            }
            }

            emailKeys.Add(new EmailKey
            {
                Key   = EmailKeyOption.Subject,
                Value = eMailSubject
            });

            emailRow.EmailKeys = emailKeys;

            var eMailMessage = new EmailMessage
            {
                To = new List <EmailAddress>
                {
                    new EmailAddress
                    {
                        Address = user.Email
                    }
                },
                Subject    = eMailSubject,
                From       = from,
                IsBodyHtml = true,
                Priority   = EmailPriorityOption.Normal,
                Body       = ConvertTemplateToString(templateText, emailRow)
            };

            _smtp.Send(eMailMessage);
        }
Пример #9
0
        public void ForgotPassword(string username)
        {
            var user = _repositoryUser
                       .Join(x => x.Person)
                       .Join(x => x.Creator)
                       .Join(x => x.RoleUserLines)
                       .Join(x => x.SessionsCreatedBy)
                       .FirstOrDefault(x => x.Username == username);

            // Kullanıcı sistemde kayıtlı değilse
            if (user == null)
            {
                throw new NotFoundException(Messages.DangerUserNotFound);
            }

            // Kullanıcı pasif durumda ise
            if (!user.IsApproved)
            {
                throw new NotApprovedException(Messages.DangerItemNotApproved);
            }

            // Kullanıcının hiç rolü yoksa
            if (user.RoleUserLines.Count <= 0)
            {
                throw new NotApprovedException(Messages.DangerUserHasNoRole);
            }

            // yeni şifre üret
            var newPassword = SecurityHelper.CreatePassword(8);

            // TODO: kullanıcıya mail at hata olursa exception fırlat



            var sessionIdList = new List <Guid>();

            // Açık kalan oturumu varsa
            if (user.SessionsCreatedBy?.Count > 0)
            {
                foreach (var session in user.SessionsCreatedBy)
                {
                    // oturum bilgileri tarihçe tablosuna alınıyor
                    _repositorySessionHistory.Add(new SessionHistory
                    {
                        Id                   = GuidHelper.NewGuid(),
                        Creator              = session.Creator,
                        CreationTime         = session.CreationTime,
                        LastModificationTime = DateTime.Now,
                        LogoutType           = SignOutOption.InvalidLogout.ToString()
                    }, true);
                    sessionIdList.Add(session.Id);
                }
            }

            // Oturumlar siliniyor
            foreach (var i in sessionIdList)
            {
                _repositorySession.Delete(_repositorySession.Get(e => e.Id == i), true);
            }

            var version = _repositoryUserHistory.Get().Where(e => e.ReferenceId == user.Id).Max(t => t.Version);

            var userHistory = user.CreateMapped <User, UserHistory>();

            userHistory.Id             = GuidHelper.NewGuid();
            userHistory.ReferenceId    = user.Id;
            userHistory.CreatorId      = user.Creator.Id;
            userHistory.IsDeleted      = false;
            userHistory.Version        = version + 1;
            userHistory.RestoreVersion = 0;
            _repositoryUserHistory.Add(userHistory, true);

            user.Password             = newPassword.ToSha512();
            user.LastModificationTime = DateTime.Now;
            user.LastModifier         = user;
            var affectedUser = _repositoryUser.Update(user, true);

            affectedUser.Password = newPassword;
            var emailUser = new EmailUser
            {
                Username     = affectedUser.Username,
                Password     = newPassword,
                CreationTime = affectedUser.CreationTime,
                Email        = affectedUser.Email,
                FirstName    = user.Person.FirstName,
                LastName     = user.Person.LastName
            };

            var emailSender = new EmailSender(_smtp, _serviceMain);

            emailSender.SendEmailToUser(emailUser, EmailTypeOption.ForgotPassword);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // button click seekios tutorial
            SeekiosTutorialButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToListTutorial();
            }));

            // button click my consomation
            HistoriqueConsommationButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.Credits.GoToCreditHistoric();
            }));

            // button click on add a seekios
            AddSeekiosButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToAddSeekios();
            }));

            // button click on map all seekios
            MapButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                if (App.CurrentUserEnvironment.LsSeekios.Count == 0)
                {
                    AlertControllerHelper.ShowAlert(Application.LocalizedString("ZeroSeekios")
                                                    , Application.LocalizedString("NeedAtLeastOneSeekios")
                                                    , Application.LocalizedString("Close"));
                }
                else
                {
                    if (App.CurrentUserEnvironment.LsSeekios.All(a => a.LastKnownLocation_latitude == App.DefaultLatitude &&
                                                                 a.LastKnownLocation_longitude == App.DefaultLongitude))
                    {
                        if (App.CurrentUserEnvironment.LsSeekios.Count == 1)
                        {
                            AlertControllerHelper.ShowAlert(Application.LocalizedString("NoPosition")
                                                            , Application.LocalizedString("OneSeekiosNewlyAdded")
                                                            , Application.LocalizedString("Close"));
                        }
                        else
                        {
                            AlertControllerHelper.ShowAlert(Application.LocalizedString("NoPosition")
                                                            , Application.LocalizedString("PluralSeekiosNewlyAdded")
                                                            , Application.LocalizedString("Close"));
                        }
                    }
                    else
                    {
                        NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                        App.Locator.LeftMenu.GoToSeekiosMapAllSeekios();
                    }
                }
            }));

            // button click on feedback
            FeedbackButton.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                var feedbackManager = BITHockeyManager.SharedHockeyManager.FeedbackManager;
                feedbackManager.ShowFeedbackListView();
                feedbackManager.ShowFeedbackComposeView();
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
            }));

            // button click on Parameter
            UserImageView.UserInteractionEnabled = true;
            UserImageView.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
            EmailUser.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
            NameUser.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
            SettingsImageView.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
            CreditsTitleLabel.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
            CreditsLabel.AddGestureRecognizer(new UITapGestureRecognizer(() =>
            {
                NavigationService.LeftMenuView.RevealViewController().RightRevealToggleAnimated(true);
                App.Locator.LeftMenu.GoToParameter();
            }));
        }