当前位置: 首页>>代码示例>>C#>>正文


C# BaseRepository.Update方法代码示例

本文整理汇总了C#中BaseRepository.Update方法的典型用法代码示例。如果您正苦于以下问题:C# BaseRepository.Update方法的具体用法?C# BaseRepository.Update怎么用?C# BaseRepository.Update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BaseRepository的用法示例。


在下文中一共展示了BaseRepository.Update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AuthorizeUser

        public OldUser AuthorizeUser(string login, string password)
        {
            using (var _userRepository = new BaseRepository<OldUser>())
            {
                //var OldUser = _userRepository.GetAllItems.FirstOrDefault(x => x.Login == login && x.Password == password);
                var user = _userRepository.Context.OldUsers.Include("Role").FirstOrDefault(x => x.Login == login && x.Password == password);
                if (user == null)
                {
                    throw new UserDoesNotExistException();
                }

                if (user.ExpirationDate < DateTime.Now)
                {
                    // session is not valid, update token
                    user.Token = Guid.NewGuid();
                }

                user.ExpirationDate = DateTime.Now.AddMinutes(20);

                if (_userRepository.Update(user).Status)
                {
                    return user;
                }
            }
            throw new UpdateException();
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:26,代码来源:AuthorizationRepository.cs

示例2: CompleteParentCuratorSurvey

        public bool CompleteParentCuratorSurvey(long childSurveysId)
        {
            using (var surveysResultRepository = new BaseRepository<SurveysResult>())
            {
                SurveysResult child = surveysResultRepository.GetAllItems.FirstOrDefault(x => x.Id == childSurveysId);
                if (child == null)
                {
                    throw new SurveysResultDoesNotExistException();
                }
                SurveysResult parent = child.Parent;
                if (parent == null)
                {
                    return false;
                }

                // Check parent methods type is CuratorGroup
                if (!String.Equals(parent.MethodsType, Constraints.KMethodsTypeCuratorGroup))
                {
                    return false;
                }

                int surveysCount = -1;
                // Require child surveys count of Curator parent
                List<SurveysMethodicsGroupItem> methodics =
                    surveysResultRepository.Context.SurveysMethodicsGroupItems.Where(x => x.SurveysResultId == parent.Id)
                        .ToList();
                if (methodics.Count == 0)
                {
                    return false;
                }

                List<SurveysPersonsGroup> surveysPersons = parent.SurveysPersonsGroups.ToList();
                if (surveysPersons.Count == 0)
                {
                    return false;
                }

                surveysCount = methodics.Count*surveysPersons.Count;

                // Check all tests of package is completed
                List<SurveysResult> childSurveys =
                    surveysResultRepository.GetAllItems.Where(x => x.Parent.Id == parent.Id).ToList();
                if (childSurveys.Select(x => x.IsCompleted).Contains(false) || childSurveys.Count != surveysCount)
                {
                    return false;
                }
                // Update parent
                parent.IsCompleted = true;
                if (!surveysResultRepository.Update(parent).Status)
                {
                    throw new UpdateException();
                }
                return true;
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:55,代码来源:SurveysResultRepository.cs

示例3: GetUserByCredentials

 public OldUser GetUserByCredentials(Guid authToken, bool updateExpDate = true, int expMinutes = 20)
 {
     using (var _repository = new BaseRepository<OldUser>())
     {
         var user = _repository.Context.OldUsers.Include("Role").FirstOrDefault(x => x.Token == authToken && DateTime.Compare(DateTime.Now, x.ExpirationDate) < 0);
         if(user == null)
         {
             throw new UnauthorizedException();
         }
         if(updateExpDate)
         {
             user.ExpirationDate = DateTime.Now.AddMinutes(expMinutes);
             if(!_repository.Update(user).Status)
             {
                 throw new UnauthorizedException();
             }
         }
         return user;
     }
 }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:20,代码来源:AuthorizationRepository.cs

示例4: UpdateGroupUser

        public void UpdateGroupUser(GroupUser groupUser, long groupId, OldUser curator)
        {
            using (var groupUserRepository = new BaseRepository<GroupUser>())
            {
                var group = groupUserRepository.Context.Groups.FirstOrDefault(x => x.Id == groupId);

                if (group == null)
                {
                    throw new PersonsGroupDoesNotExistException();
                }

                if (!String.Equals(curator.Role.Name, Constraints.KCuratorRoleName)
                    || curator.Id != group.Curator)
                {
                    throw new UserRightsException();
                }

                var updatedGroupUser = groupUserRepository.GetAllItems.FirstOrDefault(x => x.Id == groupUser.Id);
                if (updatedGroupUser == null)
                {
                    throw new UserDoesNotExistException();
                }

                if (updatedGroupUser.Group.Id != groupId)
                {
                    throw new GroupUserException();
                }

                if (String.IsNullOrWhiteSpace(groupUser.Email) || String.IsNullOrWhiteSpace(groupUser.FirstName)
                    || String.IsNullOrWhiteSpace(groupUser.LastName) || String.IsNullOrWhiteSpace(groupUser.MiddleName))
                {
                    throw new RequireFieldException();
                }

                //update  all fields except Id, code, group
                updatedGroupUser.Email = groupUser.Email;
                updatedGroupUser.BirthDate = groupUser.BirthDate;
                updatedGroupUser.Gender = groupUser.Gender;
                updatedGroupUser.FirstName = groupUser.FirstName;
                updatedGroupUser.LastName = groupUser.LastName;
                updatedGroupUser.MiddleName = groupUser.MiddleName;
                updatedGroupUser.Note = groupUser.Note;

                if (!groupUserRepository.Update(updatedGroupUser).Status)
                {
                    throw new UpdateException();
                }

            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:50,代码来源:GroupRepository.cs

示例5: UpdateGroup

        public void UpdateGroup(Group group)
        {
            if (String.IsNullOrWhiteSpace(group.Code))
            {
                throw new RequireFieldException();
            }
            using (var userRepository = new BaseRepository<OldUser>())
            {
                if (!userRepository.GetAllItems.Any(x => x.Id == group.Curator))
                {
                    throw new UserDoesNotExistException();
                }
            }
            using (var groupRepository = new BaseRepository<Group>())
            {
                var updatedGroup = groupRepository.GetAllItems.FirstOrDefault(x => x.Id == group.Id);
                if (updatedGroup == null)
                {
                    throw new PersonsGroupDoesNotExistException();
                }
                if (updatedGroup.Curator != group.Curator)
                {
                    throw new UserRightsException();
                }
                if (String.Compare(updatedGroup.Code, group.Code, StringComparison.CurrentCulture) != 0
                    &&  groupRepository.GetAllItems.Any(x => x.Curator == group.Curator && x.Code == group.Code))
                {
                    throw new GroupUniqueException();
                }
                updatedGroup.Code = group.Code;
                updatedGroup.Note = group.Note;

                if (groupRepository.Update(updatedGroup).Status)
                {
                    return;
                }
                throw new UpdateException();
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:39,代码来源:GroupRepository.cs

示例6: UpdateProfileBody

        public void UpdateProfileBody(Guid resultId, String profileBody)
        {
            using (var profileRepository = new BaseRepository<Profile>())
            {
                var findedProfile = profileRepository.Context.Profiles.Include("Result").FirstOrDefault(x => x.Id == resultId);
                if (findedProfile == null)
                {
                    throw new ResultDoesNotExistException();
                }

                findedProfile.Body = profileBody;
                findedProfile.Interpretated = true;

                if (!profileRepository.Update(findedProfile).Status)
                {
                    throw new UpdateException();
                }

            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:20,代码来源:ProfileRepository.cs

示例7: CreateProfile


//.........这里部分代码省略.........

                // Conver Data base data to Shell data
                var user = _resultRepository.GetUserByResult(resultId);
                var test = _resultRepository.GetTestByResult(resultId);
                var resultItems = _resultRepository.GetResultItemsByResult(resultId);
                var shellResult = _resultRepository.GetShellResultByResult(resultId);

                var resultConverter = new ResultConverter(user, test, resultItems);
                String shAnswers = resultConverter.FormAnswers();

                //var needProfile = ResultInterpretator.GetProfile(resultConverter);

                /*
                 * Form Profile string from DLL
                 */

                //String profileStr = @"<p>КОММУНИКАТИВНАЯ СФЕРА</p><p>Преимущественное открытое, дружеское общение с окружающими, навыки общения развиты достаточно. Стремление к активности, доминированию среди сверстников. Настойчивость в достижении поставленной цели. Уверенность в своей правоте. В значимых для себя ситуациях возможно проявление упрямства. Стремление к популярности в окружении. Достаточная высокая самоуверенность.</p><p>ЭМОЦИОНАЛЬНО-ВОЛЕВАЯ СФЕРА</p><p>Воображение недостаточно развито, мышление в основном конкретное, возможны трудности в ситуациях требующих абстрактного мышления. Возможны проявления капризности, непостоянства в значимых для себя ситуациях. Стремление уклониться от трудностей. Недостаточное постоянство в отношениях и интересах. Действия могут опережать их продуманность. Наивность, затруднения в планировании своего поведения в сочетании со стремлением уклониться от повседневных проблем и трудностей создают картину психического инфантилизма. Зависимость от сверстников, поспешность в решениях. Возможна излишняя сентиментальность. Некоторое сужение поля восприятия. Уверенность в правильности своих действий, снижение процессов рефлексии, ослабление процессов целеполагания, трудности в формировании мотивации обучения. Неудовлетворенность своим положением в группе сверстников, сочетаясь с ощущением давления со стороны семейного круга создает предиспозицию для отклонений в поведении.</p>";
                String profileStr = @"<p>Идет интерпретация</p>";

                //==============================

                //Create Folder and txt info file
                var directoryName = user.Id + "_" + test.CodeName + "_" + result.TestDate.ToString("dd.MM.yyyy_HH.mm.ss");
                var directory = Constraints.KInterpretationDirectoryPath + directoryName;
                try
                {
                    // Determine whether the directory not exists.
                    if (!Directory.Exists(directory))
                    {
                        // Try to create the directory.
                        Directory.CreateDirectory(directory);
                    }
                }
                catch (Exception)
                {
                    throw new DirectoryNotFoundException();
                }

                try
                {
                    // Create txt file info
                    var fileName = @"\info.txt";
                    var fileInfo = new FileInfo(directory + fileName);

                    if (!fileInfo.Exists)
                    {
                        //Create a file to write to.
                        using (var streamWriter = fileInfo.CreateText())
                        {
                            streamWriter.WriteLine("===========================");
                            streamWriter.WriteLine("ResultId: " + resultId);
                            streamWriter.WriteLine("===========================");
                            streamWriter.Write(user.ToString());
                            streamWriter.WriteLine();
                            streamWriter.WriteLine("===========================");
                            streamWriter.Write(test.ToString());
                            streamWriter.WriteLine("===========================");
                            streamWriter.WriteLine(result.TestDate.ToString());
                            streamWriter.WriteLine("===========================");

                            //var shellResult = resultRepo.Context.ShellResults.FirstOrDefault(x => x.ResultId == resultId);

                            //if (shellResult == null)
                            //{
                            //    throw new ResultDoesNotExistException();
                            //}
                            streamWriter.WriteLine("Method_ID in consul: " + shellResult.MethodId);
                            streamWriter.WriteLine("===========================");
                            streamWriter.WriteLine(shellResult.Answer);
                            streamWriter.WriteLine("===========================");
                            streamWriter.WriteLine(shellResult.Answer.Replace(" ",null));

                            streamWriter.Close();
                        }
                    }
                }
                catch (Exception)
                {
                    throw new FileWriteException();
                }

                // Create OldUser and Result in ConsulDB
                //WriteUserResultInConsul(result, OldUser, test, shellResult);

                // Create profile in DB
                var profile = new Profile {
                    Body = profileStr,
                    Id = resultId,
                    ImageDirectory = directoryName,

                };
                result.Profile = profile;

                if (resultRepo.Update(result).Status)
                {
                    return profile;
                }
                throw new UpdateException();
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:101,代码来源:ProfileRepository.cs

示例8: GenerateProfile

        public Object GenerateProfile(Guid resultId)
        {
            using (var resultRepo = new BaseRepository<Result>())
            {
                var result = resultRepo.GetAllItems.FirstOrDefault(x => x.Id == resultId);
                if (result == null)
                {
                    throw new ResultDoesNotExistException();
                }

                var user = _resultRepository.GetUserByResult(resultId);
                var test = _resultRepository.GetTestByResult(resultId);
                var resultItems = _resultRepository.GetResultItemsByResult(resultId);
                var shellResult = _resultRepository.GetShellResultByResult(resultId);

                #region not need now

                var profileFounded = resultRepo.Context.Profiles.FirstOrDefault(x => x.Id == resultId);
                if (profileFounded == null)
                {
                    //String profileStr = @"<p>КОММУНИКАТИВНАЯ СФЕРА</p><p>Преимущественное открытое, дружеское общение с окружающими, навыки общения развиты достаточно. Стремление к активности, доминированию среди сверстников. Настойчивость в достижении поставленной цели. Уверенность в своей правоте. В значимых для себя ситуациях возможно проявление упрямства. Стремление к популярности в окружении. Достаточная высокая самоуверенность.</p><p>ЭМОЦИОНАЛЬНО-ВОЛЕВАЯ СФЕРА</p><p>Воображение недостаточно развито, мышление в основном конкретное, возможны трудности в ситуациях требующих абстрактного мышления. Возможны проявления капризности, непостоянства в значимых для себя ситуациях. Стремление уклониться от трудностей. Недостаточное постоянство в отношениях и интересах. Действия могут опережать их продуманность. Наивность, затруднения в планировании своего поведения в сочетании со стремлением уклониться от повседневных проблем и трудностей создают картину психического инфантилизма. Зависимость от сверстников, поспешность в решениях. Возможна излишняя сентиментальность. Некоторое сужение поля восприятия. Уверенность в правильности своих действий, снижение процессов рефлексии, ослабление процессов целеполагания, трудности в формировании мотивации обучения. Неудовлетворенность своим положением в группе сверстников, сочетаясь с ощущением давления со стороны семейного круга создает предиспозицию для отклонений в поведении.</p>";
                    String profileStr = @"<p>Идет интерпретация</p>";

                    //==============================

                    //Create Folder and txt info file
                    var directoryName = user.Id + "_" + test.CodeName + "_" + result.TestDate.ToString("dd.MM.yyyy_HH.mm.ss");
                    var directory = Constraints.KInterpretationDirectoryPath + directoryName;
                    try
                    {
                        // Determine whether the directory not exists.
                        if (!Directory.Exists(directory))
                        {
                            // Try to create the directory.
                            Directory.CreateDirectory(directory);
                        }
                    }
                    catch (Exception)
                    {
                        throw new DirectoryNotFoundException();
                    }

                    try
                    {
                        // Create txt file info
                        var fileName = @"\info.txt";
                        var fileInfo = new FileInfo(directory + fileName);

                        if (!fileInfo.Exists)
                        {
                            //Create a file to write to.
                            using (var streamWriter = fileInfo.CreateText())
                            {
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine("ResultId: " + resultId);
                                streamWriter.WriteLine("===========================");
                                streamWriter.Write(user.ToString());
                                streamWriter.WriteLine();
                                streamWriter.WriteLine("===========================");
                                streamWriter.Write(test.ToString());
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(result.TestDate.ToString());
                                streamWriter.WriteLine("===========================");

                                //var shellResult = resultRepo.Context.ShellResults.FirstOrDefault(x => x.ResultId == resultId);

                                //if (shellResult == null)
                                //{
                                //    throw new ResultDoesNotExistException();
                                //}
                                streamWriter.WriteLine("Method_ID in consul: " + shellResult.MethodId);
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(shellResult.Answer);
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(shellResult.Answer.Replace(" ", null));

                                streamWriter.Close();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw new FileWriteException();
                    }

                    // Create OldUser and Result in ConsulDB
                    //WriteUserResultInConsul(result, OldUser, test, shellResult);

                    // Create profile in DB
                    var profile = new Profile
                    {
                        Body = profileStr,
                        Id = resultId,
                        ImageDirectory = directoryName,

                    };
                    result.Profile = profile;

                    if (!resultRepo.Update(result).Status)
                    {
//.........这里部分代码省略.........
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:101,代码来源:ProfileRepository.cs

示例9: UpdateCuratorPerson

        public void UpdateCuratorPerson(long curatorId, long personId, Person person)
        {
            using (var personRepository = new BaseRepository<Person>())
            {
                Client curator = personRepository.Context.Clients.FirstOrDefault(x => x.Id == curatorId);
                if (curator == null)
                {
                    throw new UserDoesNotExistException();
                }

                Person foundedPerson = personRepository.GetAllItems.FirstOrDefault(x => x.Id == personId && x.Curator.Id == curatorId);
                if (foundedPerson == null)
                {
                    throw new PersonDoesNotExistException();
                }

                // All fields can be updated except CuratorId!!!!!

                if (person.PersonsGroup != null)
                {
                    PersonsGroup personsGroup =
                    personRepository.Context.PersonsGroups.FirstOrDefault(x => x.Id == person.PersonsGroup.Id);
                    if (person.PersonsGroup.Id != 0 && personsGroup == null)
                    {
                        throw new PersonsGroupDoesNotExistException();
                    }

                    if (person.PersonsGroup.Id == 0)
                    {
                        PersonsGroup groupRelated = foundedPerson.PersonsGroup;
                        if (groupRelated != null)
                        {
                            groupRelated.Persons.Remove(foundedPerson);
                            foundedPerson.PersonsGroup = null;
                            personRepository.Context.SaveChanges();
                        }

                    }
                    else
                    {
                        foundedPerson.PersonsGroup = personsGroup;
                    }
                }

                // If email updated and not equals current - check unique
                // select Email from Persons where Curator_Id = curatorId
                if (!String.IsNullOrWhiteSpace(person.Email) && !String.Equals(person.Email, foundedPerson.Email, StringComparison.OrdinalIgnoreCase))
                {
                    if (personRepository.GetAllItems.Where(x => x.Curator.Id == curatorId).Select(x => x.Email).Contains(person.Email))
                    {
                        throw new PersonEmailException();
                    }
                    foundedPerson.Email = person.Email;
                }

                if (person.FirstName != null)
                {
                    foundedPerson.FirstName = person.FirstName;
                }
                if (person.LastName != null)
                {
                    foundedPerson.LastName = person.LastName;
                }
                if (person.MiddleName != null)
                {
                    foundedPerson.MiddleName = person.MiddleName;
                }
                if (person.BirthDate.HasValue)
                {
                    foundedPerson.BirthDate = person.BirthDate;
                }
                if (person.Note != null)
                {
                    foundedPerson.Note = person.Note;
                }

                foundedPerson.Gender = person.Gender;

                if (!personRepository.Update(foundedPerson).Status)
                {
                    throw new UpdateException();
                }
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:84,代码来源:CuratorRepository.cs

示例10: GenerateDataProfile


//.........这里部分代码省略.........
                //if (String.Equals(test.CodeName, Constraints.KKotCodeName))
                //{
                //    // Get answer str from SurveyShellResult.Answer
                //    SurveysShellResult shellResult =
                //        conclusionRepository.Context.SurveysShellResults.FirstOrDefault(
                //            x => x.SurveyResultId == surveysResultId);
                //    if (shellResult != null)
                //    {
                //        answerStr = shellResult.Answer;
                //    }
                //}
                //else
                //{
                    answerStr = ResultConverter.GenerateAnswerString(test.CodeName, surveysAnswerContents);
                //}

                // Form profile string
                String profile = String.Empty;
                switch (test.CodeName)
                {
                    case Constraints.KKettel16ACodeName:
                    case Constraints.KKettel16BCodeName:
                        KettelMethod kettel = new KettelMethod(person.Gender, person.BirthDate.Value, answerStr);
                        kettel.CreateProfile();
                        KettelOutput kettelOutput = new KettelOutput();
                        kettelOutput.CreateOutputJson(kettel);
                        profile = JsonHelper.JsonSerializer<KettelOutput>(kettelOutput);
                        break;

                    case Constraints.KSelfAppraisalCodeName:
                        SelfAppraisalMethod selfAppraisal = new SelfAppraisalMethod(answerStr);
                        selfAppraisal.CreateProfile();
                        SelfAppraisalOutput selfAppraisalOutput = new SelfAppraisalOutput();
                        selfAppraisalOutput.CreateOutputJson(selfAppraisal);
                        profile = JsonHelper.JsonSerializer<SelfAppraisalOutput>(selfAppraisalOutput);
                        break;

                    case Constraints.KSondiCodeName:
                        SondiMethod sondi = new SondiMethod(answerStr);
                        sondi.CreateProfile();
                        sondi.CreateFormulaAffection();
                        sondi.CreateDMFactor();
                        sondi.CreateSocialityFactor();
                        SondiOutput sondiOutput = new SondiOutput();
                        sondiOutput.CreateOutputJson(sondi);
                        profile = JsonHelper.JsonSerializer<SondiOutput>(sondiOutput);
                        break;

                    case Constraints.KKotCodeName:
                        KotMethod kot = new KotMethod(answerStr);
                        kot.CreateProfile();
                        KotOutput kotOutput = new KotOutput();
                        kotOutput.CreateOutputJson(kot);
                        profile = JsonHelper.JsonSerializer<KotOutput>(kotOutput);
                        break;

                    case Constraints.KShutzCodeName:
                        ShutzMethod shutz = new ShutzMethod(answerStr);
                        shutz.CreateProfile();
                        ShutzOutput shutzOutput = new ShutzOutput();
                        shutzOutput.CreateOutputJson(shutz);
                        profile = JsonHelper.JsonSerializer<ShutzOutput>(shutzOutput);
                        break;

                    case Constraints.KLusherPairCodeName:
                        profile = LusherPairMethod.GetColorString(answerStr);
                        break;

                    case Constraints.KMmpiCodeName:
                        MmpiMethod mmpi = new MmpiMethod(answerStr, person.Gender);
                        mmpi.CreateProfile();
                        profile = mmpi.CutProfileStr;
                        break;

                    default:
                        break;
                }

                // Save profile in Conclusion.Data
                Service service =
                    conclusionRepository.Context.Services.FirstOrDefault(
                        x =>
                        x.MethodsId == surveysResult.MethodsId &&
                        String.Equals(x.MethodsType, surveysResult.MethodsType) &&
                        String.Equals(x.ConclusionType.Code, Constraints.KConclusionTypeProfile));

                if (service != null)
                {
                    Conclusion conclusion =
                        conclusionRepository.GetAllItems.FirstOrDefault(
                            x => x.SurveysResult.Id == surveysResultId && x.Service.Id == service.Id);
                    conclusion.Data = profile;
                    if (!conclusionRepository.Update(conclusion).Status)
                    {
                        throw new UpdateException();
                    }
                }
                return profile;
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:101,代码来源:ConclusionRepository.cs

示例11: RegisterNew

        // TODO : Hack
        public OldUser RegisterNew(OldUser oldUser)
        {
            using (var userRepository = new BaseRepository<OldUser>())
            {

                // Check password Validation (6 sevbols at least)
                if (oldUser.Password.Length < 6)
                {
                    throw new UserPasswordException();
                }

                var foundedUser =
                    userRepository.Context.OldUsers.Include("Role").FirstOrDefault(
                        x => String.Equals(x.Login, oldUser.Login) && String.Equals(x.Email, oldUser.Email));
                if (foundedUser != null)
                {
                    // Update password and non required fields; Gender; BirthDate
                    foundedUser.Password = oldUser.Password;
                    foundedUser.FirstName = oldUser.FirstName;
                    foundedUser.LastName = oldUser.LastName;
                    foundedUser.MiddleName = oldUser.MiddleName;

                    foundedUser.Gender = oldUser.Gender;
                    foundedUser.BirthDate = oldUser.BirthDate;

                    foundedUser.Token = Guid.NewGuid();
                    foundedUser.ExpirationDate = DateTime.Now.AddMinutes(20);

                    if (!userRepository.Update(foundedUser).Status)
                    {
                        throw new UpdateException();
                    }

                    return foundedUser;
                }

                foundedUser = userRepository.Context.OldUsers.Include("Role").FirstOrDefault(x => String.Equals(x.Login, oldUser.Login));
                var emailUser = userRepository.Context.OldUsers.Include("Role").FirstOrDefault(x => String.Equals(x.Email, oldUser.Email));
                if (foundedUser != null && emailUser != null)
                {
                    var userWithNewEmail =
                        userRepository.Context.OldUsers.Include("Role").FirstOrDefault(x => String.Equals(x.Email, oldUser.Email));
                    if (userWithNewEmail != null)
                    {
                        // OldUser with new Email exists
                        throw new UserEmailException();
                    }

                    // Update all non-required credentials and Email, Gender, BirthDate
                    foundedUser.Email = oldUser.Email;

                    foundedUser.Password = oldUser.Password;
                    foundedUser.FirstName = oldUser.FirstName;
                    foundedUser.LastName = oldUser.LastName;
                    foundedUser.MiddleName = oldUser.MiddleName;

                    foundedUser.Gender = oldUser.Gender;
                    foundedUser.BirthDate = oldUser.BirthDate;

                    foundedUser.Token = Guid.NewGuid();
                    foundedUser.ExpirationDate = DateTime.Now.AddMinutes(20);

                    if (!userRepository.Update(foundedUser).Status)
                    {
                        throw new UpdateException();
                    }

                    return foundedUser;
                }

                foundedUser = userRepository.Context.OldUsers.Include("Role").FirstOrDefault(x => String.Equals(x.Email, oldUser.Email));
                if (foundedUser != null)
                {

                    var userWithNewLogin =
                        userRepository.GetAllItems.FirstOrDefault(x => String.Equals(x.Login, oldUser.Login));
                    if (userWithNewLogin != null)
                    {
                        // OldUser with new Login exists
                        throw new UserLoginException();
                    }

                    // Update all non-required credentials and Login, Gender, BirthDate
                    foundedUser.Login = oldUser.Login;

                    foundedUser.Password = oldUser.Password;
                    foundedUser.FirstName = oldUser.FirstName;
                    foundedUser.LastName = oldUser.LastName;
                    foundedUser.MiddleName = oldUser.MiddleName;

                    foundedUser.Gender = oldUser.Gender;
                    foundedUser.BirthDate = oldUser.BirthDate;

                    foundedUser.Token = Guid.NewGuid();
                    foundedUser.ExpirationDate = DateTime.Now.AddMinutes(20);

                    if (!userRepository.Update(foundedUser).Status)
                    {
                        throw new UpdateException();
//.........这里部分代码省略.........
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:101,代码来源:AuthorizationRepository.cs

示例12: CompleteParentPackageSurvey

        public bool CompleteParentPackageSurvey(long childSurveysId)
        {
            using (var surveysResultRepository = new BaseRepository<SurveysResult>())
            {
                SurveysResult child = surveysResultRepository.GetAllItems.FirstOrDefault(x => x.Id == childSurveysId);
                if (child == null)
                {
                    throw new SurveysResultDoesNotExistException();
                }
                SurveysResult parent = child.Parent;
                if (parent == null)
                {
                    return false;
                }

                // Check parent methods type is Package
                if (!String.Equals(parent.MethodsType, Constraints.KMethodsTypePackage))
                {
                    return false;
                }

                Package package = surveysResultRepository.Context.Packages.FirstOrDefault(x => x.Id == parent.MethodsId);
                if (package == null)
                {
                    return false;
                }

                int surveysCount = -1;
                // Require child surveys count of Package parent
                if (package.Tests != null)
                {
                    surveysCount = package.Tests.Count;
                    if (String.Equals(package.CodeName, "Package7") || String.Equals(package.CodeName, "Package8"))
                    {
                        ++surveysCount;
                    }
                }

                // Check all tests of package is completed
                List<SurveysResult> childSurveys =
                    surveysResultRepository.GetAllItems.Where(x => x.Parent.Id == parent.Id).ToList();
                if (childSurveys.Select(x => x.IsCompleted).Contains(false) || childSurveys.Count != surveysCount)
                {
                    return false;
                }
                // Update parent
                parent.IsCompleted = true;
                if (!surveysResultRepository.Update(parent).Status)
                {
                    throw new UpdateException();
                }
                return true;
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:54,代码来源:SurveysResultRepository.cs

示例13: CreateSurveyShellResultForTest

        public SurveysShellResult CreateSurveyShellResultForTest(long surveysResultId, List<SurveysAnswerContent> surveysAnswerContents)
        {
            using (var shellResultRepository = new BaseRepository<SurveysShellResult>())
            {
                SurveysResult surveysResult =
                    shellResultRepository.Context.SurveysResults.FirstOrDefault(x => x.Id == surveysResultId);
                if (surveysResult == null)
                {
                    throw new SurveysResultDoesNotExistException();
                }

                // Surveys shell result existing
                SurveysShellResult foundedSurveyShellResult =
                    shellResultRepository.GetAllItems.FirstOrDefault(x => x.SurveyResultId == surveysResultId);

                // surveysResult.Methods_type == "Test"
                if (!String.Equals(surveysResult.MethodsType, Constraints.KMethodsTypeTest))
                {
                    return null;
                }
                Test test = shellResultRepository.Context.Tests.FirstOrDefault(x => x.Id == surveysResult.MethodsId);
                if (test == null)
                {
                    throw new TestPackageDoesNotExistException();
                }

                Person person =
                    shellResultRepository.Context.Persons.FirstOrDefault(x => x.Id == surveysResult.Person.Id);
                if (person == null)
                {
                    throw new PersonDoesNotExistException();
                }

                int shellMethodId = ResultConverter.GetConsulMethodId(test.CodeName);

                String answerStr = ResultConverter.GenerateAnswerString(test.CodeName, surveysAnswerContents, true);

                if (foundedSurveyShellResult == null)
                {
                    // Create row in surveysShellResult
                    SurveysShellResult surveysShellResult = new SurveysShellResult()
                    {
                        MethodsId = surveysResult.MethodsId,
                        MethodsType = surveysResult.MethodsType,
                        PersonId = person.Id,
                        ShellMethodId = shellMethodId,
                        TestDate = surveysResult.Date,
                        Answer = answerStr,
                        SurveyResultId = surveysResult.Id
                    };
                    if (!shellResultRepository.Create(surveysShellResult).Status)
                    {
                        throw new CreateException();
                    }
                    return surveysShellResult;
                }
                else
                {
                    foundedSurveyShellResult.MethodsId = surveysResult.MethodsId;
                    foundedSurveyShellResult.MethodsType = surveysResult.MethodsType;
                    foundedSurveyShellResult.PersonId = person.Id;
                    foundedSurveyShellResult.ShellMethodId = shellMethodId;
                    foundedSurveyShellResult.TestDate = surveysResult.Date;
                    foundedSurveyShellResult.Answer = answerStr;
                    foundedSurveyShellResult.SurveyResultId = surveysResult.Id;

                    if (!shellResultRepository.Update(foundedSurveyShellResult).Status)
                    {
                        throw new UpdateException();
                    }
                    return foundedSurveyShellResult;
                }

            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:75,代码来源:SurveysResultRepository.cs

示例14: CompleteSurveyResult

 public void CompleteSurveyResult(long surveysResultId, bool isCompleted = true)
 {
     using (var surveyResultRepository = new BaseRepository<SurveysResult>())
     {
         SurveysResult surveysResult =
             surveyResultRepository.GetAllItems.FirstOrDefault(x => x.Id == surveysResultId);
         if (surveysResult == null)
         {
             throw new SurveysResultDoesNotExistException();
         }
         surveysResult.IsCompleted = isCompleted;
         if (!surveyResultRepository.Update(surveysResult).Status)
         {
             throw new UpdateException();
         }
     }
 }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:17,代码来源:SurveysResultRepository.cs

示例15: UpdatePersonsGroup

        public void UpdatePersonsGroup(long curatorId, long groupId, PersonsGroup group)
        {
            using (var personsGroupRepository = new BaseRepository<PersonsGroup>())
            {
                Client curator = personsGroupRepository.Context.Clients.FirstOrDefault(x => x.Id == curatorId);
                if (curator == null)
                {
                    throw new UserDoesNotExistException();
                }

                PersonsGroup foundedGroup =
                    personsGroupRepository.GetAllItems.FirstOrDefault(x => x.Id == groupId && x.Curator.Id == curatorId);
                if (foundedGroup == null)
                {
                    throw new PersonsGroupDoesNotExistException();
                }

                if (!String.IsNullOrWhiteSpace(group.Name) && !String.Equals(group.Name, foundedGroup.Name))
                {
                    // Check unique Name
                    // SELECT Name FROM PersonsGroup WHERE Curator_Id = curatorId AND Name  = group.Name
                    if (personsGroupRepository.GetAllItems.Any(x => x.Curator.Id == curatorId && String.Equals(x.Name, group.Name)))
                    {
                        throw new PersonsGroupNameException();
                    }
                    foundedGroup.Name = group.Name;
                }

                if (group.Note != null)
                {
                    foundedGroup.Note = group.Note;
                }

                if (!personsGroupRepository.Update(foundedGroup).Status)
                {
                    throw new UpdateException();
                }
            }
        }
开发者ID:sergiygladkyy,项目名称:mbo,代码行数:39,代码来源:CuratorRepository.cs


注:本文中的BaseRepository.Update方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。