public String[] Validate(UserProfileModel user, ClimbingContext db, CompetitionModel comp)
        {
            PersonModel      p;
            Comp_ClimberTeam e;

            return(Validate(user, db, comp, out p, out e));
        }
        public CompetitionEditModel(CompetitionModel model, ClimbingContext db)
        {
            this.Iid                 = model.Iid;
            this.ShortName           = model.ShortName;
            this.FullName            = model.Name;
            this.StartDate           = model.Start;
            this.StopDate            = model.End;
            this.ApplicationsEndDate = model.ApplicationsEnd;

            this.Region                  = model.Region;
            this.RegionId                = model.RegionId;
            this.Lead                    = model.Lead;
            this.Speed                   = model.Speed;
            this.Boulder                 = model.Boulder;
            this.ageGroups               = new List <Comp_AgeGroupEdit>();
            this.AllowLateApps           = model.AllowLateAppl;
            this.ApplicationsEditEndDate = model.ApplicationsEditEnd;
            this.RequireSignature        = model.SignApplications;
            this.AllowMultipleTeams      = model.AllowMultipleTeams;
            var grpList = db.AgeGroups.ToList();

            grpList.Sort();
            foreach (var agr in grpList)
            {
                ageGroups.Add(new Comp_AgeGroupEdit(agr, (agr.CompetitionGroups.Count(cg => cg.CompetitionId == model.Iid) > 0)));
            }
        }
Ejemplo n.º 3
0
        public static T GetRequestParameter <T>(this APISignedRequest request, ClimbingContext db, out CompetitionModel comp) where T : APIBaseRequest
        {
            if (request == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            comp = db.Competitions.Find(request.CompID);
            if (comp == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            T retValue = request.Request as T;

            if (retValue == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            byte[] publicKeyData = comp[CompetitionParamType.SignatureKey].BinaryValue;
            if (publicKeyData == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotImplemented);
            }
            if (!ValidateDSASignature(retValue, request.Signature, publicKeyData))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }
            return(retValue);
        }
Ejemplo n.º 4
0
 public override bool ResetPasswordWithToken(string token, string newPassword)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.Find(GetUserIdFromPasswordResetToken(token));
         if (usr == null)
         {
             return(false);
         }
         if (usr.PasswordTokenExpirationTime != null && usr.PasswordTokenExpirationTime.Value < DateTime.UtcNow)
         {
             return(false);
         }
         ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(usr.Name, newPassword, false);
         OnValidatingPassword(e);
         if (e.Cancel)
         {
             return(false);
         }
         usr.Token = null;
         usr.PasswordTokenExpirationTime = null;
         usr.SetPassword(newPassword);
         usr.Inactive = false;
         db.SaveChanges();
         return(true);
     }
 }
 public SeedingHelperTests()
 {
     this.context = new ClimbingContext(
         new DbContextOptionsBuilder <ClimbingContext>().UseInMemoryDatabase($"Db{Guid.NewGuid()}").Options);
     this.teamsServiceSut  = new TeamsService(this.context, this.TeamsServiceLogger);
     this.seedingHelperSut = new SeedingHelper(this.context, this.teamsServiceSut, this.SeedingHelperLogger);
 }
        private string[] GetRolesForUser(string username, long?compID, long?regionID)
        {
            using (var db = new ClimbingContext())
            {
                var user = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase));
                if (user == null)
                {
                    return(new string[0]);
                }
                IEnumerable <UserRoleModel> roles = user.Roles.ToArray();
                if (compID != null && compID.HasValue)
                {
                    roles = roles.Where(r => r.CompID != null || r.CompID.Value == compID.Value);
                }
                else
                {
                    roles = roles.Where(r => r.CompID == null);
                }

                if (regionID != null && regionID.HasValue)
                {
                    roles = roles.Where(r => r.RegionID != null && r.RegionID.Value == regionID.Value);
                }
                else
                {
                    roles = roles.Where(r => r.RegionID == null);
                }

                var res = roles.Select(r => ((RoleEnum)r.RoleId).ToString()).ToArray();
                return(res);
            }
        }
        public override void OnException(ExceptionContext filterContext)
        {
            if (!(filterContext.ExceptionHandled || (filterContext.Exception is System.Web.Http.HttpResponseException)))
            {
                try
                {
                    DateTime      dt     = DateTime.UtcNow;
                    StringBuilder exData = new StringBuilder();
                    exData.AppendFormat("Date:           {0}{1}", dt.ToShortDateString(), Environment.NewLine);
                    exData.AppendFormat("Time:           {0}{1}", dt.ToLongTimeString(), Environment.NewLine);
                    exData.AppendFormat("Controller:     {0}{1}", filterContext.Controller.GetType(), Environment.NewLine);
                    exData.AppendFormat("IsChildAction:  {0}{1}", filterContext.IsChildAction, Environment.NewLine);
                    exData.AppendFormat("Exception Data: {1}{0}", GetExceptionData(filterContext.Exception, 0), Environment.NewLine);

                    ClimbingContext      db = new ClimbingContext();
                    IEnumerable <String> emailList;
                    try { emailList = db.UserRoles.Where(r => r.CompID == null && r.RegionID == null && r.RoleId >= (int)RoleEnum.Admin).Select(r => r.User.Email ?? String.Empty).ToList().Distinct(); }
                    catch { emailList = new List <string> {
                                "*****@*****.**"
                            }; }
                    Parallel.ForEach(emailList.Where(e => !String.IsNullOrEmpty(e)),
                                     u => MailService.SendMessage(u, "Unhandled Exception",
                                                                  exData.ToString(), true));
                }
                catch { }
            }
            base.OnException(filterContext);
        }
Ejemplo n.º 8
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            ClimbingContext db = new ClimbingContext();
            String          prefixCode;

            if (this.IidParent == null)
            {
                prefixCode = String.Empty;
            }
            else
            {
                var pReg = db.Regions.Find(IidParent);
                prefixCode = (pReg == null) ? String.Empty : (pReg.SymCode ?? String.Empty);
            }
            var fullCode = prefixCode + SymCode;

            if (fullCode.Length > RegionModel.CODE_LENGTH)
            {
                yield return(new ValidationResult(
                                 String.Format("Длина кода должна быть не более {0} символов", RegionModel.CODE_LENGTH - prefixCode.Length),
                                 new String[] { "SymCode" }));
            }
            if (!String.IsNullOrEmpty(fullCode))
            {
                if (db.Regions.Count(r => r.Iid != (this.Iid ?? 0) && r.SymCode.Equals(fullCode, StringComparison.Ordinal)) > 0)
                {
                    yield return(new ValidationResult("Регион с таким кодом уже сществует", new String[] { "SymCode" }));
                }
            }
        }
Ejemplo n.º 9
0
 public override bool HasLocalAccount(int userId)
 {
     using (var db = new ClimbingContext())
     {
         var u = db.UserProfiles.Find(userId);
         return(u != null);
     }
 }
        private PersonModel FindSuitablePerson(ClimbingContext db)
        {
            var nameList = db.People.Where(p => p.Surname.Equals(Surname, StringComparison.OrdinalIgnoreCase) &&
                                           p.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToList();

            return(nameList.FirstOrDefault(p => p.GenderProperty == this.GenderP.Value &&
                                           p.YearOfBirth == this.YearOfBirth.Value));
        }
        public CompetitionEditModel(ClimbingContext db)
            : this()
        {
            var agr = db.AgeGroups.ToList();

            agr.Sort();
            foreach (var a in agr)
            {
                this.ageGroups.Add(new Comp_AgeGroupEdit(a, false));
            }
        }
Ejemplo n.º 12
0
 public override bool ValidateUser(string username, string password)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase));
         if (usr == null || usr.Inactive)
         {
             return(false);
         }
         return(usr.CheckPassword(password));
     }
 }
        private static AgeGroupModel GetAgeGroup(ClimbingContext db, Dictionary <int, AgeGroupModel> groups, Comp_AgeGroupEdit agr)
        {
            AgeGroupModel a;

            if (groups.ContainsKey(agr.GroupId))
            {
                a = groups[agr.GroupId];
            }
            else
            {
                a = db.AgeGroups.Find(agr.GroupId);
                groups.Add(agr.GroupId, a);
            }
            return(a);
        }
Ejemplo n.º 14
0
 public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase));
         if (usr == null)
         {
             return(null);
         }
         return(new MembershipUser("ClimbingMembershipProvider",
                                   username, usr.Iid, usr.Email, null, null, !usr.Inactive, usr.Inactive,
                                   new DateTime(), new DateTime(), new DateTime(), new DateTime(), new DateTime()));
     }
     //return GetUser(usr.UserId, userIsOnline);
 }
Ejemplo n.º 15
0
 public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
 {
     using (var db = new ClimbingContext())
     {
         var db_usr = db.UserProfiles.Find(providerUserKey);
         if (db_usr == null)
         {
             return(null);
         }
         MembershipUser mu = new MembershipUser("ClimbingMembershipProvider",
                                                db_usr.Name, db_usr.Iid, db_usr.Email, null, null, !db_usr.Inactive, db_usr.Inactive,
                                                new DateTime(), new DateTime(), new DateTime(), new DateTime(), new DateTime());
         return(mu);
     }
 }
Ejemplo n.º 16
0
 public override int GetUserIdFromPasswordResetToken(string token)
 {
     using (var db = new ClimbingContext())
     {
         var user = db.UserProfiles.FirstOrDefault(u => u.Token.Equals(token, StringComparison.OrdinalIgnoreCase));
         if (user == null)
         {
             return(-1);
         }
         else
         {
             return(user.Iid);
         }
     }
 }
Ejemplo n.º 17
0
        private MailService()
        {
            db     = new ClimbingContext();
            client = new SmtpClient();
            SmtpSection sect      = (SmtpSection)WebConfigurationManager.GetSection("system.net/mailSettings/smtp");
            string      emailFrom = WebConfigurationManager.AppSettings["emailFrom"];

            adFrom      = new MailAddress(emailFrom, sect.From);
            client.Host = sect.Network.Host;
            client.UseDefaultCredentials = sect.Network.DefaultCredentials;
            if (!client.UseDefaultCredentials)
            {
                client.Credentials = new NetworkCredential(sect.Network.UserName, sect.Network.Password);
            }
            client.EnableSsl = sect.Network.EnableSsl;
        }
Ejemplo n.º 18
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            using (var db = new ClimbingContext())
            {
                var u = db.UserProfiles.Find(user.ProviderUserKey);
                if (u == null)
                {
                    return;
                }

                /*if (db.UserProfiles.Count(usr => usr.Iid != u.Iid && usr.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase)) > 0)
                 *  throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);*/
                u.Email    = user.Email;
                u.Inactive = user.IsLockedOut;
                db.SaveChanges();
            }
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            ClimbingContext db   = new ClimbingContext();
            var             comp = db.Competitions.Find(this.Iid);

            if (comp == null)
            {
                yield return(new ValidationResult(String.Format("Invalid ID={0}", Iid)));
            }
            else
            {
                if (comp.Climbers.Count > 0)
                {
                    yield return(new ValidationResult("На соревнования есть заявленные участнки. Сначала удалите их"));
                }
            }
        }
Ejemplo n.º 20
0
 public override bool DeleteAccount(string userName)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.SingleOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         if (usr == null)
         {
             return(false);
         }
         if (usr.Roles.Count(r => r.RoleId == (int)RoleEnum.Admin) > 0 &&
             db.UserRoles.Count(ur => ur.UserId != usr.Iid && ur.RoleId == (int)RoleEnum.Admin) < 1)
         {
             //throw new ArgumentException(String.Format("Can\'t delete the last administrator {0}", userName));
             return(false);
         }
         db.UserProfiles.Remove(usr);
         db.SaveChanges();
         return(true);
     }
 }
Ejemplo n.º 21
0
 public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)
 {
     using (var db = new ClimbingContext())
     {
         var usr = db.UserProfiles.SingleOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         if (usr == null)
         {
             return(null);
         }
         string token;
         do
         {
             token = GenerateToken();
         } while (db.UserProfiles.Count(u => u.Token.Equals(token, StringComparison.OrdinalIgnoreCase)) > 0);
         usr.Token = token;
         usr.PasswordTokenExpirationTime = DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow);
         db.SaveChanges();
         return(token);
     }
 }
Ejemplo n.º 22
0
        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary <string, object> values)
        {
            if (String.IsNullOrEmpty(password))
            {
                password = Membership.GeneratePassword(this.minRequiredPasswordLength + 10, this.minRequiredNonAlphanumericCharacters + 1);
            }
            else
            {
                ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(userName, password, true);
                OnValidatingPassword(e);
                if (e.Cancel)
                {
                    return(null);
                }
            }
            using (var db = new ClimbingContext())
            {
                var usr = db.UserProfiles.Create();
                usr.Name = userName;
                usr.SetPassword(password);
                usr.Inactive = true;

                if (requireConfirmation)
                {
                    string token;
                    do
                    {
                        token = GenerateToken();
                    } while (db.UserProfiles.Count(u => u.Token.Equals(token, StringComparison.OrdinalIgnoreCase)) > 0);
                    usr.Token = token;
                }
                else
                {
                    usr.Token = String.Empty;
                }
                db.UserProfiles.Add(usr);
                db.SaveChanges();
                return(usr.Token);
            }
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <ClimbingContext>(null);

                try
                {
                    using (var context = new ClimbingContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("RemoteDbConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        private static Fixture CreateFixture()
        {
            var fixture = new Fixture();

            fixture.Customize(new AutoMoqCustomization());
            fixture.Register <ClimbingContext>(() =>
            {
                var ctx = new ClimbingContext(
                    new DbContextOptionsBuilder <ClimbingContext>().UseInMemoryDatabase(DatabaseName).Options);
                new ContextSeedingHelper(ctx).Seed();
                return(ctx);
            });

            fixture.Register <IUnitOfWork>(() => fixture.Create <ClimbingContext>());
            fixture.Register <IContextHelper>(() => new SimpleContextHelper());
            fixture.Register <ISeedingHelper>(() => new SimpleSeedingHelper());
            fixture.Register <IPageParameters>(() => fixture.Create <PageParameters>());

            RegisterPagedCollection <TeamFacade>(fixture);

            return(fixture);
        }
Ejemplo n.º 25
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (!ValidateUser(username, oldPassword))
            {
                return(false);
            }
            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, newPassword, false);

            OnValidatingPassword(e);
            if (e.Cancel)
            {
                return(false);
            }
            using (var db = new ClimbingContext())
            {
                var usr = db.UserProfiles.First(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase));

                usr.SetPassword(newPassword);
                db.SaveChanges();
                return(true);
            }
        }
Ejemplo n.º 26
0
 public override bool ConfirmAccount(string userName, string accountConfirmationToken)
 {
     using (var db = new ClimbingContext())
     {
         UserProfileModel usr;
         if (String.IsNullOrEmpty(userName))
         {
             usr = db.UserProfiles.Find(GetUserIdFromPasswordResetToken(accountConfirmationToken));
         }
         else
         {
             usr = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
         }
         if (usr == null)
         {
             return(false);
         }
         usr.Inactive = false;
         usr.Token    = String.Empty;
         usr.PasswordTokenExpirationTime = null;
         db.SaveChanges();
         return(true);
     }
 }
        public String[] Validate(UserProfileModel user, ClimbingContext db, CompetitionModel comp, out PersonModel foundPerson, out Comp_ClimberTeam existingApp)
        {
            foundPerson = null;
            existingApp = null;
            this.Team   = (this.TeamId == null) ? null : db.Regions.Find(this.TeamId);
            if (this.Team == null)
            {
                return new String[] { "Команда не выбрана" }
            }
            ;
            long regionId = this.TeamId.Value;

            if (!comp.AllowedToEdit(user))
            {
                return new String[] { "У вас нет прав на изменение заявок" }
            }
            ;
            PrepareName();
            this.AgeChange    = this.YearOfBirth.Value.ToString();
            this.GenderChange = this.GenderP.GetFriendlyValue();
            List <String> errors   = new List <string>();
            int           age      = comp.Start.Year - this.YearOfBirth.Value;
            var           agrGroup = comp.AgeGroups.ToList().FirstOrDefault(gr =>
                                                                            gr.AgeGroup.GenderProperty == this.GenderP.Value &&
                                                                            (gr.AgeGroup.MaxAge ?? int.MaxValue) >= age &&
                                                                            (gr.AgeGroup.MinAge ?? 0) <= age);

            if (agrGroup == null)
            {
                errors.Add(String.Format("Участник {0} {1} не входит ни в одну возрастную группу", Surname, Name));
            }
            else
            {
                this.GroupId   = agrGroup.Iid;
                this.GroupName = agrGroup.AgeGroup.FullName;
            }
            Comp_ClimberTeam exApp = null;

            if (this.ApplicationId != null)
            {
                exApp = db.CompetitionClimberTeams.Find(this.ApplicationId);
                if (exApp == null)
                {
                    this.ApplicationId = null;
                }
                else
                {
                    if (exApp.RegionId != regionId || exApp.Climber.CompId != comp.Iid)
                    {
                        errors.Add(String.Format("У вас нет прав для редактирования заявки {0} {1}", Surname, Name));
                    }
                }
            }
            if (exApp == null && !comp.AllowedToAdd(user))
            {
                errors.Add("У вас нет прав для заявки");
            }
            else if (exApp != null && !exApp.AllowedEdit(user))
            {
                errors.Add("У вас нет прав для корректировки заявки");
            }
            if (errors.Count > 0)
            {
                return(errors.ToArray());
            }
            var climber = this.FindSuitablePerson(db);

            if (climber != null && !comp.AllowMultipleTeams)
            {
                var curCompReg = climber.Competitions.FirstOrDefault(c => c.CompId == comp.Iid);
                if (curCompReg != null)
                {
                    StringBuilder exTeams = new StringBuilder();
                    foreach (var ct in curCompReg.Teams.Where(ct => ct.RegionId != regionId))
                    {
                        if (exTeams.Length > 0)
                        {
                            exTeams.Append(", ");
                        }
                        exTeams.Append(ct.Region.Name);
                    }
                    if (exTeams.Length > 0)
                    {
                        return new String[] { "Участник уже заявлен от других команд: " + exTeams.ToString() }
                    }
                    ;
                }
            }

            if (exApp != null && (climber == null || climber.Iid != exApp.Climber.PersonId))
            {
                var  oldClimber = exApp.Climber.Person;
                bool changed    = false;
                if (!oldClimber.Surname.Equals(Surname, StringComparison.Ordinal) ||
                    !oldClimber.Name.Equals(Name, StringComparison.Ordinal))
                {
                    //this.DisplayName = String.Format("{0} {1} => {2}", oldClimber.Surname, oldClimber.Name, DisplayName);
                    changed = true;
                }
                if (this.YearOfBirth.Value != oldClimber.DateOfBirth.Year)
                {
                    this.AgeChange = String.Format("{0} => {1}", oldClimber.DateOfBirth.Year, AgeChange);
                    if (!changed)
                    {
                        changed = true;
                    }
                }
                if (this.GenderP.Value != oldClimber.GenderProperty)
                {
                    this.GenderChange = String.Format("{0} => {1}", oldClimber.GenderProperty.GetFriendlyValue(), GenderChange);
                    if (!changed)
                    {
                        changed = true;
                    }
                }
                if (changed && !comp.AllowedToAdd(user))
                {
                    errors.Add("Замена запрещена.");
                }
            }
            if (climber != null)
            {
                var compApply = climber.Competitions.Where(c => c.CompId == comp.Iid).ToList();
                if (compApply.Count(ca => ca.Teams.Count(ct => ct.RegionId == regionId && (exApp == null || exApp != null && exApp.Iid != ct.Iid)) > 0) > 0)
                {
                    errors.Add(String.Format("Участник {0} {1} уже заявлен от Вашего региона", Surname, Name));
                }
            }
            foundPerson = climber;
            existingApp = exApp;
            return(errors.ToArray());
        }

        #endregion
    }
}
Ejemplo n.º 28
0
        public void LoadUsers(ClimbingContext db)
        {
            this.Users = new List <RegionAdminModel>();
            if (this.Iid != null)
            {
                //Админы региона
                Users.AddRange(
                    db.UserRoles
                    .Where(r => r.RegionID == this.Iid &&
                           r.CompID == null &&
                           r.RoleId >= (int)RoleEnum.Admin)
                    .Select(r => r.User)
                    .ToList()
                    .Distinct()
                    .Select(u => new RegionAdminModel
                {
                    UserId     = u.Iid,
                    UserName   = u.Name,
                    UserEmail  = u.Email ?? String.Empty,
                    UserRegion = (u.RegionId == null) ? String.Empty : u.Region.Name,
                    IsAdmin    = true
                }));

                //пользователи региона
                Users.AddRange(
                    db.UserProfiles
                    .Where(u => u.RegionId == this.Iid)
                    .ToList()
                    .Where(u => Users.Count(au => au.UserId == u.Iid) < 1)
                    .Select(u => new RegionAdminModel
                {
                    UserId     = u.Iid,
                    UserName   = u.Name,
                    UserEmail  = u.Email ?? String.Empty,
                    UserRegion = u.Region.Name,
                    IsAdmin    = false
                }));
            }

            this.Users.AddRange(
                db.UserRoles
                .Where(r => (r.RegionID ?? 0) == (IidParent ?? 0) &&
                       r.CompID == null &&
                       r.RoleId >= (int)RoleEnum.Admin)
                .Select(r => r.User)
                .ToList()
                .Distinct()
                .Where(u => Users.Count(au => au.UserId == u.Iid) < 1)
                .Select(u => new RegionAdminModel
            {
                UserId     = u.Iid,
                UserName   = u.Name,
                UserEmail  = u.Email ?? String.Empty,
                UserRegion = u.RegionId == null ? String.Empty : u.Region.Name,
                IsAdmin    = false
            }));
            this.Users.Sort((a, b) =>
            {
                var n = a.UserRegion.CompareTo(b.UserRegion);
                if (n != 0)
                {
                    return(n);
                }
                return(a.UserName.CompareTo(b.UserName));
            });
        }
Ejemplo n.º 29
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            bool createInactive = true;

            using (var db = new ClimbingContext())
            {
                if (db.UserProfiles.Count(u => u.Name.Equals(username, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }
                if (String.IsNullOrEmpty(password))
                {
                    password = Membership.GeneratePassword(minRequiredPasswordLength + 10, minRequiredNonAlphanumericCharacters + 1);
                }
                else
                {
                    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
                    OnValidatingPassword(args);
                    if (args.Cancel)
                    {
                        status = MembershipCreateStatus.InvalidPassword;
                        return(null);
                    }
                }
                if (String.IsNullOrEmpty(email))
                {
                    status = MembershipCreateStatus.InvalidEmail;
                    return(null);
                }
                if (requiresUniqueEmail && db.UserProfiles.Count(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase)) > 0)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return(null);
                }
                try
                {
                    string token = null;
                    if (createInactive)
                    {
                        do
                        {
                            token = GenerateToken();
                        }while (db.UserProfiles.Count(p => p.Token.Equals(token, StringComparison.InvariantCultureIgnoreCase)) > 0);
                    }
                    var upm = db.UserProfiles.Create();
                    upm.Name = username;
                    upm.SetPassword(password);
                    upm.Email    = email;
                    upm.Inactive = createInactive;
                    upm.Token    = token;
                    upm.PasswordTokenExpirationTime = null;
                    db.UserProfiles.Add(upm);
                    db.SaveChanges();
                    status = MembershipCreateStatus.Success;
                    return(GetUser(username, false));
                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                    return(null);
                }
            }
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            ValidationResult vRes;
            DateTime?        val;

            vRes = validateExpression(m => m.StartDateText, out val);
            if (vRes == null)
            {
                this.StartDate = val;
            }
            else
            {
                yield return(vRes);
            }

            vRes = validateExpression(m => m.StopDateText, out val);
            if (vRes == null)
            {
                this.StopDate = val;
            }
            else
            {
                yield return(vRes);
            }

            vRes = validateExpression(m => m.ApplicationsEndDateString, out val);
            if (vRes == null)
            {
                this.ApplicationsEndDate = val;
            }
            else
            {
                yield return(vRes);
            }

            vRes = validateExpression(m => m.ApplicationsEditEndDateString, out val);
            if (vRes == null)
            {
                this.ApplicationsEditEndDate = val;
            }
            else
            {
                yield return(vRes);
            }

            DateTime startDate  = this.StartDate ?? DateTime.MinValue;
            DateTime stopDate   = this.StopDate ?? DateTime.MaxValue;
            DateTime appEnd     = this.ApplicationsEndDate ?? DateTime.MinValue;
            DateTime appEditEnd = this.ApplicationsEditEndDate ?? DateTime.MinValue;

            if (stopDate < startDate)
            {
                yield return(new ValidationResult("Дата окончания должна быть больше или равной дате начала", new String[] { "StopDate" }));
            }
            if (appEditEnd < appEnd)
            {
                yield return(new ValidationResult("Дата окончания корректировок заявок должна быть больше или равной дате окончания заявок", new String[] { "ApplicationsEditEndDate" }));
            }
            if (appEditEnd > startDate)
            {
                yield return(new ValidationResult("Дата окончания корректировки заявок должан быть меньше или равной дате начала", new String[] { "ApplicationsEditEndDate" }));
            }
            if (!(Lead || Speed || Boulder))
            {
                yield return(new ValidationResult("Виды не выбраны"));
            }
            if (ageGroups == null || ageGroups.Count(g => g.Confirmed) < 1)
            {
                yield return(new ValidationResult("Группы не выбраны"));
            }
            if (ageGroups != null)
            {
                ClimbingContext db = new ClimbingContext();
                Dictionary <int, AgeGroupModel> groups = new Dictionary <int, AgeGroupModel>();
                foreach (var agr in ageGroups.Where(g => g.Confirmed))
                {
                    AgeGroupModel a = GetAgeGroup(db, groups, agr);
                    if (a == null)
                    {
                        yield return(new ValidationResult(String.Format("Группа с ID={0} не найдена.", agr.GroupId)));

                        continue;
                    }
                    int minAge      = a.MinAge ?? int.MinValue;
                    int maxAge      = a.MaxAge ?? int.MaxValue;
                    var crossGroups = ageGroups
                                      .Where(g => g.Confirmed)
                                      .Select(g => GetAgeGroup(db, groups, g))
                                      .Where(g => g != null)
                                      .Where(g => g.Iid != a.Iid)
                                      .Where(g => g.GenderCode == a.GenderCode &&
                                             (minAge >= (g.MinAge ?? int.MinValue) && minAge <= (g.MaxAge ?? int.MaxValue) ||
                                              maxAge >= (g.MinAge ?? int.MinValue) && maxAge <= (g.MaxAge ?? int.MaxValue)
                                             )).ToList();
                    if (crossGroups.Count < 1)
                    {
                        continue;
                    }
                    crossGroups.Sort();
                    StringBuilder sb = new StringBuilder();
                    foreach (var g in crossGroups)
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append(", ");
                        }
                        sb.Append(g.FullName);
                    }
                    yield return(new ValidationResult(String.Format("Группа {0} пересекается с группами {1}", a.FullName, sb.ToString())));
                }
            }
        }