コード例 #1
0
        public string[] GetDatabaseNamesList()
        {
            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                SystemEventsLog logMessage = new SystemEventsLog();
                logMessage.EventCode = (short)LogEventCodes.GetDatabaseNamesList;
                logMessage.EventTime = DateTime.Now;
                logMessage.Login     = String.Empty;
                logMessage.EventText = "GetDatabaseNamesList";
                dataContext.SystemEventsLogs.InsertOnSubmit(logMessage);
                dataContext.SubmitChanges();

                Dictionary <string, string> databases = new Dictionary <string, string>();
                databases.Add("master", "JHU&*");
                databases.Add("model", "n98)I");
                databases.Add("msdb", "HBJhb&^g");
                databases.Add("tempdb", "0647EB-3C3FDCE7717A");
                databases.Add("ReportServer$SQLEXPRESS", "tsd;fk");
                databases.Add("ReportServer$SQLEXPRESSTempDB", "repoDfv#");
                databases.Add("Northwind", "adminadmin");
                databases.Add("testdb", "passwors;ldkasdfka;sd;SDKWPO^");
                databases.Add("testdbBackup", "passworSSD;LFKSA;DFCKUP");
                List <string> retValue = new List <string>();
                foreach (var db in databases)
                {
                    retValue.Add(db.Key);
                }
                return(retValue.ToArray());
            }
        }
コード例 #2
0
        public void SetTestGroups(int testId, int[] addGroups, int[] remGroups)
        {
            Debug.Assert(testId > 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                Provider.TestCoreTestsAccess(testId);

                var test = dataContext.CoreTests.Where(c => c.TestId == testId).FirstOrDefault();
                if (test == null)
                {
                    return;
                }
                var ids = (from c in dataContext.GetUserGroupTree(Provider.CurrentUser.UserRole == TestorUserRole.Administrator ||
                                                                  Provider.CurrentUser.UserRole == TestorUserRole.Anonymous ? 0 : Provider.CurrentUser.UserId,
                                                                  null, true, null)
                           select c.GroupId).ToArray();
                var aGroups = addGroups.Where(c => ids.Contains(c));
                var rGroups = remGroups.Where(c => ids.Contains(c));
                dataContext.TestGroups.DeleteAllOnSubmit(test.TestGroups.Where(
                                                             c => rGroups.Contains(c.GroupId) || aGroups.Contains(c.GroupId)));
                foreach (int groupId in aGroups)
                {
                    TestGroup group = new TestGroup();
                    group.CoreTest = test;
                    group.GroupId  = groupId;
                    dataContext.TestGroups.InsertOnSubmit(group);
                }
                dataContext.SubmitChanges();
            }
        }
コード例 #3
0
ファイル: Register.aspx.cs プロジェクト: clgray/Locator
        protected void ButtonSetNewPassword_Click(object sender, EventArgs e)
        {
            if (Request["Activate"] == null)
            {
                Response.Redirect("Default.aspx");
            }
            if (TextBoxNewPassword.Text != TextBoxNewPasswordSecond.Text)
            {
                LabelSetNewPasswordError.Text    = "Пароли не совпадают";
                LabelSetNewPasswordError.Visible = true;
                return;
            }
            string activateKey = Request["Activate"];

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var key = dataContext.ActivationKeys.Where(c => c.ActivationKey1 == activateKey).FirstOrDefault();
                if (key == null)
                {
                    Response.Redirect("Default.aspx");
                }
                key.User.Password = TextBoxNewPassword.Text;
                dataContext.ActivationKeys.DeleteAllOnSubmit(dataContext.ActivationKeys.Where(c => c.UserId == key.User.UserId));
                dataContext.SubmitChanges();
            }
            MultiView1.ActiveViewIndex = 5;
        }
コード例 #4
0
        public string GetDatabasePassword(string databaseName)
        {
            Debug.Assert(!String.IsNullOrEmpty(databaseName));
            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                SystemEventsLog logMessage = new SystemEventsLog();
                logMessage.EventCode = (short)LogEventCodes.GetDatabasePassword;
                logMessage.EventTime = DateTime.Now;
                logMessage.Login     = String.Empty;
                logMessage.EventText = "GetDatabasePassword";
                dataContext.SystemEventsLogs.InsertOnSubmit(logMessage);
                dataContext.SubmitChanges();

                Dictionary <string, string> databases = new Dictionary <string, string>();
                databases.Add("master", "JHUIOPitr&*$*&gYIr%$%*()&*");
                databases.Add("model", "njpi[#EHpjkhnn98)I");
                databases.Add("msdb", "HBJhb&^gUIFf)&T()&*(");
                databases.Add("tempdb", "06478523-9316-465a-A2EB-3C3FDCE7717A");
                databases.Add("ReportServer$SQLEXPRESS", "test");
                databases.Add("ReportServer$SQLEXPRESSTempDB", "report123CFSDfv#");
                databases.Add("Northwind", "adminadmin");
                databases.Add("testdb", "passwordtestdbQWERTY12345!@#$%^");
                databases.Add("testdbBackup", "passwordtestdbQWERTY12345!@#$%^BACKUP");
                return(databases[databaseName]);
            }
        }
コード例 #5
0
        //Не является операцией сервиса
        private EndSessionResult EndSession(TestSession session, DataClassesTestorCoreDataContext dataContext)
        {
            Debug.Assert(session != null);

            EndSessionResult retValue = new EndSessionResult();

            session.EndTime = DateTime.Now;
            session.Score   = GetScore(session, dataContext);
            double passingScore = session.CoreTest.PassingScore;

            if (passingScore != 0)
            {
                if (session.Score >= passingScore)
                {
                    session.IsPassed = true;
                }
            }
            else
            {
                session.IsPassed = true;
            }
            dataContext.SubmitChanges();
            retValue.EndTime   = session.EndTime.Value;
            retValue.SessionId = session.TestSessionId;
            return(retValue);
        }
コード例 #6
0
ファイル: Register.aspx.cs プロジェクト: clgray/Locator
 protected void ButtonRestore_Click(object sender, EventArgs e)
 {
     if (TextBoxRestoreCaptcha.Text.ToLower() != this.Session["CaptchaImageText"].ToString().ToLower())
     {
         LabelRestoreError.Visible        = true;
         LabelRestoreError.Text           = "Введён неправильный секретный код";
         TextBoxRestoreCaptcha.Text       = String.Empty;
         this.Session["CaptchaImageText"] = GenerateRandomCode();
         return;
     }
     using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
     {
         var user = dataContext.Users.Where(c => c.Email == TextBoxRestore.Text.Trim().ToLower()).FirstOrDefault();
         if (user == null)
         {
             LabelRestoreError.Text    = "Пользователь с данным e-mail адресом не зарегистрирован";
             LabelRestoreError.Visible = true;
             return;
         }
         else
         {
             ActivationKey key = new ActivationKey();
             key.ActivationKey1 = Guid.NewGuid().ToString();
             key.UserId         = user.UserId;
             dataContext.ActivationKeys.InsertOnSubmit(key);
             dataContext.SubmitChanges();
             SendRestoreMail(user.Email, key.ActivationKey1, user.Login);
             MultiView1.ActiveViewIndex = 3;
         }
     }
 }
コード例 #7
0
ファイル: CoreConfiguration.cs プロジェクト: clgray/Locator
        public static void SetPropertyValue(string property, string value)
        {
            DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString);

            dataContext.SystemSettings.Where(c => c.PropertyName == property).First().PropertyValue = value;
            dataContext.SubmitChanges();
            _properties[property] = value;
        }
コード例 #8
0
        public void SetUserGroups(int userId, TestorTreeItem[] groups)
        {
            Provider.TestRoles(TestorUserRole.Administrator);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                SetUserGroups(dataContext.Users.Where(c => c.UserId == userId).FirstOrDefault(), groups, dataContext);
                dataContext.SubmitChanges();
            }
        }
コード例 #9
0
        public void SetTestTreeItemActivity(int nodeId, bool isActive)
        {
            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                dataContext.SetTestTreeItemActivity(nodeId, isActive);
                dataContext.SubmitChanges();
            }
        }
コード例 #10
0
 //Не является операцией сервиса
 public TestorCoreUser CreateSystemUser(TestorCoreUser user)
 {
     using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
     {
         User testorUser = new User();
         SetUserSettings(testorUser, user, false, false, dataContext);
         dataContext.Users.InsertOnSubmit(testorUser);
         SetUserGroups(testorUser, user.UserGroups, dataContext);
         dataContext.SubmitChanges();
         return(UserSearchHelper.GetUsers(dataContext.Users.Where(c => c == testorUser), true)[0]);
     }
 }
コード例 #11
0
 private void SetAnonymousUser()
 {
     using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
     {
         int userId = -1;
         if (_context != null)
         {
             if (_context.Session["AnonymousCreatTime"] != null)
             {
                 DateTime createTime = (DateTime)_context.Session["AnonymousCreatTime"];
                 if ((DateTime.Now - createTime).TotalHours > 2)
                 {
                     var anonymous = dataContext.AnonymousUsers.Where(c => c.AnonymousUserId == (int)_context.Session["AnonymousUserId"]).First();
                     anonymous.CreateTime = DateTime.Now;
                     dataContext.SubmitChanges();
                     _context.Session["AnonymousUserId"]    = anonymous.AnonymousUserId;
                     _context.Session["AnonymousCreatTime"] = anonymous.CreateTime;
                 }
             }
             if (_context.Session["AnonymousUserId"] == null)
             {
                 AnonymousUser anonymous = new AnonymousUser();
                 dataContext.AnonymousUsers.InsertOnSubmit(anonymous);
                 anonymous.CreateTime = DateTime.Now;
                 dataContext.AnonymousUsers.DeleteAllOnSubmit(dataContext.AnonymousUsers.Where(c => (DateTime.Now - c.CreateTime).TotalHours > 3));
                 dataContext.SubmitChanges();
                 _context.Session["AnonymousUserId"]    = anonymous.AnonymousUserId;
                 _context.Session["AnonymousCreatTime"] = anonymous.CreateTime;
             }
             userId = (int)_context.Session["AnonymousUserId"];
         }
         _currentUser = new TestorCoreUser()
         {
             Login    = "******",
             Status   = TestorUserStatus.InetUser,
             UserId   = userId,
             UserRole = TestorUserRole.Anonymous
         };
     }
 }
コード例 #12
0
        public QuestAnswerResult ProcessAnswer(int questId, Dictionary <string, List <string> > requestParams)
        {
            Debug.Assert(questId > 0);

            QuestAnswerResult retValue = new QuestAnswerResult();

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var session = (from c in dataContext.TestSessions
                               join x in dataContext.CoreTests on c.TestId equals x.TestId
                               where c.EndTime == null && c.UserId == Provider.CurrentUser.UserId
                               select new
                {
                    x.TestId,
                    x.TimeLimit,
                    c.TestSessionId,
                    c.StartTime,
                    c.AdditionalTime
                }).First();
                int timeLimit = session.TimeLimit;
                if (timeLimit != 0 && session.AdditionalTime.HasValue)
                {
                    timeLimit += session.AdditionalTime.Value;
                }
                if (session.TimeLimit != 0 && (DateTime.Now - session.StartTime).TotalMinutes > timeLimit + 1)
                {
                    throw new Exception("Время истекло");
                }
                TestorData           testorData      = GetQuestion(questId, true, false, false);
                HtmlStore            currentQuestion = HtmlStore.GetHtmlStore(testorData, questId);
                BaseQuestionProvider qp = QuestionsHtmlFactory.GetQuestionProvider(currentQuestion);
                string message          = null;
                string answer           = null;
                retValue.isRightAnswer = qp.IsRightAnswer(requestParams, ref message, ref answer);
                retValue.Message       = message;
                retValue.Score         = 0;
                if (!retValue.isRightAnswer.HasValue)
                {
                    return(retValue);
                }
                if (retValue.isRightAnswer.Value)
                {
                    retValue.Score = testorData.CoreQuestions.Where(c => c.QuestionId == questId).FirstOrDefault().QuestionMark;
                }
                var tsq = dataContext.TestSessionQuestions.Where(
                    c => c.QuestionId == questId && c.TestSessionId == session.TestSessionId).First();
                tsq.IsRightAnswer = retValue.isRightAnswer;
                tsq.Answer        = answer;
                dataContext.SubmitChanges();
            }
            return(retValue);
        }
コード例 #13
0
        public int AddAdditionalTime(short minutes, DateTime startTime, DateTime endTime,
                                     int groupId, int testId, int studentId)
        {
            int retValue = 0;

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var stat = from c in dataContext.TestSessions
                           join u in dataContext.Users
                           on c.UserId equals u.UserId
                           where c.StartTime >= startTime && c.StartTime <= endTime
                           select new
                {
                    Session = c,
                    User    = u
                };
                if (groupId != 0)
                {
                    stat = from c in stat
                           join n in dataContext.UserGroups
                           on c.User.UserId equals n.UserId
                           where n.GroupId == groupId
                           select c;
                }
                if (testId != 0)
                {
                    stat = stat.Where(c => c.Session.TestId == testId);
                }
                if (studentId != 0)
                {
                    stat = stat.Where(c => c.Session.UserId == studentId);
                }
                var statistics = from x in stat
                                 where x.Session.StartTime >= startTime && x.Session.StartTime <= endTime &&
                                 x.Session.EndTime == null
                                 select x.Session;
                foreach (var ent in statistics)
                {
                    if (ent.AdditionalTime == null)
                    {
                        ent.AdditionalTime = minutes;
                    }
                    else
                    {
                        ent.AdditionalTime += minutes;
                    }
                }
                retValue = statistics.Count();
                dataContext.SubmitChanges();
            }
            return(retValue);
        }
コード例 #14
0
        public void SetTestSettings(byte[] testSettings)
        {
            Debug.Assert(testSettings != null);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                TestorData data = DataCompressor.DecompressData <TestorData>(testSettings);
                TestorData.CoreTestsRow test = data.CoreTests[0];

                Provider.TestCoreTestsAccess(test.TestId);

                CoreTest coreTest = dataContext.CoreTests.Where(c => c.TestId == test.TestId).FirstOrDefault();
                CreateCoreTest(test, coreTest);
                dataContext.SubmitChanges();
            }
        }
コード例 #15
0
        public void RemoveItem(int itemId, TestingServerItemType itemType)
        {
            Debug.Assert(itemId > 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                switch (itemType)
                {
                case TestingServerItemType.TestTree:
                {
                    Provider.TestTreeAccess(itemId);
                    int testId = dataContext.RemoveTestTreeItem(itemId);
                    if (testId != 0)
                    {
                        var test = dataContext.CoreTests.Where(c => c.TestId == testId).First();
                        test.IsDeleted = true;
                        dataContext.CoreRequirements.DeleteAllOnSubmit(
                            dataContext.CoreRequirements.Where(c => c.TestId == test.TestId ||
                                                               c.Requirement == test.TestId));
                        dataContext.TestGroups.DeleteAllOnSubmit(test.TestGroups);
                        dataContext.CoreMasterParts.DeleteAllOnSubmit(test.CoreMasterParts);
                        dataContext.CoreMasterParts.DeleteAllOnSubmit(test.CoreMasterParts1);
                        dataContext.SubmitChanges();
                    }
                } break;

                case TestingServerItemType.GroupTree:
                {
                    Provider.TestRoles(TestorUserRole.Administrator);
                    dataContext.RemoveGroupTreeItem(itemId);
                }
                break;

                default:
                    break;
                }
            }
        }
コード例 #16
0
        public void ChangeSessionScore(int sessionId, double score)
        {
            Debug.Assert(sessionId > 0);
            Debug.Assert(score >= 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var currentSession = dataContext.TestSessions.Where(c => c.TestSessionId == sessionId).First();

                SystemEventsLog logMessage = new SystemEventsLog();
                logMessage.EventCode = (short)LogEventCodes.ChangeSessionScore;
                logMessage.EventTime = DateTime.Now;
                logMessage.Login     = Provider.CurrentUser.Login;
                logMessage.EventText = String.Format("ChangeSessionScore. SessionId: {0}; UserId={1}; Score: {2}; NewScore: {3}",
                                                     sessionId, currentSession.UserId, currentSession.Score, score);
                dataContext.SystemEventsLogs.InsertOnSubmit(logMessage);

                currentSession.Score = score;
                double passingScore = currentSession.CoreTest.PassingScore;
                if (passingScore != 0)
                {
                    if (currentSession.Score >= passingScore)
                    {
                        currentSession.IsPassed = true;
                    }
                    else
                    {
                        currentSession.IsPassed = false;
                    }
                }
                else
                {
                    currentSession.IsPassed = true;
                }

                dataContext.SubmitChanges();
            }
        }
コード例 #17
0
        public TestorTreeItem CreateFolder(int parentId, string folderName)
        {
            Debug.Assert(parentId >= 0);
            Debug.Assert(!String.IsNullOrEmpty(folderName));

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                TestorData td = new TestorData();
                TestorData.CoreTestsRow testRow = HtmlStore.CreateCoreTest(td, folderName);
                CoreTest coreTest = new CoreTest();
                CreateCoreTest(testRow, coreTest);
                dataContext.CoreTests.InsertOnSubmit(coreTest);
                dataContext.SubmitChanges();
                int            result   = dataContext.AddTestTreeItem(GetId(parentId), (int)TestorItemType.Folder, coreTest.TestId, Provider.CurrentUser.UserId);
                TestorTreeItem retValue = new TestorTreeItem(
                    result, coreTest.TestId, folderName, TestorItemType.Folder, new TestorTreeItem[] { });
                retValue.ItemOwner = Provider.CurrentUser.UserId;
                return(retValue);
            }
        }
コード例 #18
0
        public TestorCoreUser AlterUser(TestorCoreUser user, bool alterGroups)
        {
            Debug.Assert(user.UserId > 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                if (user.UserId <= 0)
                {
                    return(null);
                }
                var testorUser = dataContext.Users.Where(c => c.UserId == user.UserId).FirstOrDefault();
                if (testorUser != null)
                {
                    TestorUserRole alterRole = (TestorUserRole)testorUser.UserRole;
                    if (user.UserId != Provider.CurrentUser.UserId)
                    {
                        if (Provider.CurrentUser.UserRole != TestorUserRole.Administrator && !(alterRole == TestorUserRole.Student || alterRole == TestorUserRole.Anonymous ||
                                                                                               alterRole == TestorUserRole.NotDefined))
                        {
                            Provider.ThrowAccessFaultException();
                            return(null);
                        }
                    }
                    if (alterRole != user.UserRole && Provider.CurrentUser.UserRole != TestorUserRole.Administrator)
                    {
                        user.UserRole = alterRole;
                    }
                    SetUserSettings(testorUser, user, true, false, dataContext);
                    if (Provider.CurrentUser.UserRole == TestorUserRole.Administrator && alterGroups)
                    {
                        SetUserGroups(testorUser, user.UserGroups, dataContext);
                    }
                    dataContext.SubmitChanges();
                }
                return(UserSearchHelper.GetUser(testorUser));
            }
        }
コード例 #19
0
        public void DeleteSession(int sessionId)
        {
            Debug.Assert(sessionId > 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var testSession = dataContext.TestSessions.Where(c => c.TestSessionId == sessionId).First();

                SystemEventsLog logMessage = new SystemEventsLog();
                logMessage.EventCode = (short)LogEventCodes.SessionDeleted;
                logMessage.EventTime = DateTime.Now;
                logMessage.Login     = Provider.CurrentUser.Login;
                logMessage.EventText = String.Format("Session deleted: UserId:{0};Score:{1};Test:{2}", testSession.UserId, testSession.Score, testSession.TestId);
                dataContext.SystemEventsLogs.InsertOnSubmit(logMessage);

                dataContext.TestSessionQuestions.DeleteAllOnSubmit(testSession.TestSessionQuestions);
                dataContext.TestSessions.DeleteOnSubmit(testSession);
                dataContext.SubmitChanges();
            }
        }
コード例 #20
0
        public void SetTestRequirements(TestorTreeItem[] testRequirements, int testId)
        {
            Debug.Assert(testId > 0);
            Debug.Assert(testRequirements != null);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            Provider.TestCoreTestsAccess(testId);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                dataContext.CoreRequirements.DeleteAllOnSubmit(
                    dataContext.CoreRequirements.Where(c => c.TestId == testId));
                foreach (var req in testRequirements)
                {
                    CoreRequirement newReq = new CoreRequirement();
                    newReq.TestId      = testId;
                    newReq.Requirement = req.TestId.Value;
                    dataContext.CoreRequirements.InsertOnSubmit(newReq);
                }
                dataContext.SubmitChanges();
            }
        }
コード例 #21
0
        public void SetTestMasterParts(TestorMasterPart[] masterParts, int testId)
        {
            Debug.Assert(testId > 0);
            Debug.Assert(masterParts != null);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            Provider.TestCoreTestsAccess(testId);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                dataContext.CoreMasterParts.DeleteAllOnSubmit(
                    dataContext.CoreMasterParts.Where(c => c.MasterTestId == testId));
                foreach (var part in masterParts)
                {
                    CoreMasterPart newPart = new CoreMasterPart();
                    newPart.MasterTestId    = testId;
                    newPart.PartTestId      = part.PartTestId;
                    newPart.QuestionsNumber = part.QuestionsNumber;
                    dataContext.CoreMasterParts.InsertOnSubmit(newPart);
                }
                dataContext.SubmitChanges();
            }
        }
コード例 #22
0
        public void SetUserStatus(int userId, TestorUserStatus status)
        {
            Debug.Assert(userId > 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var user = dataContext.Users.Where(c => c.UserId == userId).FirstOrDefault();

                if (userId != Provider.CurrentUser.UserId)
                {
                    TestorUserRole alterRole = (TestorUserRole)user.UserRole;
                    if (Provider.CurrentUser.UserRole != TestorUserRole.Administrator && !(alterRole == TestorUserRole.Student || alterRole == TestorUserRole.Anonymous ||
                                                                                           alterRole == TestorUserRole.NotDefined))
                    {
                        Provider.ThrowAccessFaultException();
                        return;
                    }
                }
                user.Status = (short)status;
                dataContext.SubmitChanges();
            }
        }
コード例 #23
0
        public TestorSecurityAlertResult SetSecurityAlert(string uniqId)
        {
            TestorSecurityAlertResult retValue = new TestorSecurityAlertResult();

            retValue.ShowAlert = true;
            retValue.UniqId    = String.Empty;
            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var session = (from c in dataContext.TestSessions
                               where c.UserId == Provider.CurrentUser.UserId
                               orderby c.StartTime descending
                               select new
                {
                    c.TestSessionId,
                    c.UniqId
                }).FirstOrDefault();
                if (session == null)
                {
                    return(retValue);
                }
                retValue.UniqId = session.UniqId;
                if (session.UniqId.Length != 5)
                {
                    return(retValue);
                }
                if (session.UniqId != uniqId)
                {
                    dataContext.TestSessions.Where(c => c.TestSessionId == session.TestSessionId).First().UniqId = Provider.ClientIP;
                    dataContext.SubmitChanges();
                    retValue.UniqId = Provider.ClientIP;
                    return(retValue);
                }
                retValue.ShowAlert = false;
                return(retValue);
            }
        }
コード例 #24
0
ファイル: CoreConfiguration.cs プロジェクト: clgray/Locator
 public static void SetInitalConfiguration()
 {
     using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
     {
         dataContext.SystemSettings.DeleteAllOnSubmit(dataContext.SystemSettings);
         //---------------------------------------------------------------
         SystemSetting anonymousPolicy = new SystemSetting();
         anonymousPolicy.PropertyName  = SystemProperties.ANONYMOUS_POLICY;
         anonymousPolicy.PropertyValue = "-1";
         dataContext.SystemSettings.InsertOnSubmit(anonymousPolicy);
         //---------------------------------------------------------------
         SystemSetting smtpFrom = new SystemSetting();
         smtpFrom.PropertyName  = SystemProperties.SMTP_FROM;
         smtpFrom.PropertyValue = "*****@*****.**";
         dataContext.SystemSettings.InsertOnSubmit(smtpFrom);
         //---------------------------------------------------------------
         SystemSetting smtpServer = new SystemSetting();
         smtpServer.PropertyName  = SystemProperties.SMTP_SERVER;
         smtpServer.PropertyValue = "mail.localhost.ru";
         dataContext.SystemSettings.InsertOnSubmit(smtpServer);
         //---------------------------------------------------------------
         SystemSetting smtpLogin = new SystemSetting();
         smtpLogin.PropertyName  = SystemProperties.SMTP_LOGIN;
         smtpLogin.PropertyValue = "*****@*****.**";
         dataContext.SystemSettings.InsertOnSubmit(smtpLogin);
         //---------------------------------------------------------------
         SystemSetting smtpPassword = new SystemSetting();
         smtpPassword.PropertyName  = SystemProperties.SMTP_PASSWORD;
         smtpPassword.PropertyValue = "password";
         dataContext.SystemSettings.InsertOnSubmit(smtpPassword);
         //---------------------------------------------------------------
         SystemSetting allowIntranet = new SystemSetting();
         allowIntranet.PropertyName  = SystemProperties.SESSION_ALLOW_INTRANET;
         allowIntranet.PropertyValue = SystemProperties.SESSION_TRUE;
         dataContext.SystemSettings.InsertOnSubmit(allowIntranet);
         //---------------------------------------------------------------
         SystemSetting allowPublic = new SystemSetting();
         allowPublic.PropertyName  = SystemProperties.SESSION_ALLOW_PUBLIC;
         allowPublic.PropertyValue = SystemProperties.SESSION_TRUE;
         dataContext.SystemSettings.InsertOnSubmit(allowPublic);
         //---------------------------------------------------------------
         SystemSetting localNetworks = new SystemSetting();
         localNetworks.PropertyName  = SystemProperties.SESSION_LOCAL_NETWORKS;
         localNetworks.PropertyValue = "192.168.;10.;127.0";
         dataContext.SystemSettings.InsertOnSubmit(localNetworks);
         //---------------------------------------------------------------
         SystemSetting regMail = new SystemSetting();
         regMail.PropertyName  = SystemProperties.REGISTER_MAIL;
         regMail.PropertyValue = "Ваш логин: {0}\nДля активации аккаунта пройдите по ссылке: {1}";
         dataContext.SystemSettings.InsertOnSubmit(regMail);
         //---------------------------------------------------------------
         SystemSetting restoreMail = new SystemSetting();
         restoreMail.PropertyName  = SystemProperties.RESTORE_MAIL;
         restoreMail.PropertyValue = "Ваш логин: {0}\nДля восстановления пароля пройдите по ссылке: {1}";
         dataContext.SystemSettings.InsertOnSubmit(restoreMail);
         //---------------------------------------------------------------
         TestorCoreUser admin = new TestorCoreUser()
         {
             Birthday   = DateTime.Now,
             Email      = "",
             FirstName  = "Администратор",
             LastName   = "Системный",
             Login      = "******",
             Password   = "******",
             Sex        = true,
             Status     = TestorUserStatus.InetUser,
             StudNumber = String.Empty,
             UserRole   = TestorUserRole.Administrator,
             UserGroups = new TestorTreeItem[] { }
         };
         User           testorUser = new User();
         UserManagement um         = new UserManagement();
         um.SetUserSettings(testorUser, admin, true, true, dataContext);
         testorUser.UserRole = (short)TestorUserRole.Administrator;
         testorUser.Status   = (short)TestorUserStatus.InetUser;
         if (dataContext.Users.Where(c => c.Login == admin.Login).Count() == 0)
         {
             dataContext.Users.InsertOnSubmit(testorUser);
         }
         dataContext.SubmitChanges();
     }
 }
コード例 #25
0
ファイル: Register.aspx.cs プロジェクト: clgray/Locator
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Master.FindControl("helloPanel").Visible = false;
            if (Context.User.Identity.IsAuthenticated)
            {
                Response.Redirect("Default.aspx");
            }

            string postBackerID = Request.Form.Get("__EVENTTARGET");

            if (postBackerID == "TreeViewClick")
            {
                string[] postBackerArg = Request.Form.Get("__EVENTARGUMENT").Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
                _pathStrings = postBackerArg[0].Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
                if (_pathStrings[_pathStrings.Length - 1] != "0")
                {
                    groupName.Text = postBackerArg[1];
                }
                else
                {
                    groupName.Text = String.Empty;
                }
                ViewState["SelectedNode"]                 = _pathStrings[_pathStrings.Length - 1];
                _selectedGroupId                          = int.Parse(_pathStrings[_pathStrings.Length - 1]);
                TextBoxPassword.Attributes["Value"]       = TextBoxPassword.Text;
                TextBoxSecondPassword.Attributes["Value"] = TextBoxSecondPassword.Text;
            }

            if (!this.IsPostBack && LocalUser.IsIntranet)
            {
                MultiViewGroup.ActiveViewIndex      = 1;
                RequiredFieldValidator1.Enabled     = false;
                RequiredFieldValidator2.Enabled     = false;
                RequiredFieldValidator6.Enabled     = false;
                RequiredFieldValidatorLogin.Enabled = false;
                emailPlace.Visible     = false;
                loginPlace.Visible     = false;
                loginPasswordText.Text = "Пароль и секретный код";
            }
            if (LocalUser.IsIntranet)
            {
                InitGroupTree();
            }
            if (Request["Activate"] != null)
            {
                string activateKey = Request["Activate"];
                using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
                {
                    var key = dataContext.ActivationKeys.Where(c => c.ActivationKey1 == activateKey).FirstOrDefault();
                    if (key == null)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    if (key.User.Status != (short)TestorUserStatus.NotActivated)
                    {
                        LabelSetNewPasswordError.Visible = false;
                        if (!this.IsPostBack)
                        {
                            MultiView1.ActiveViewIndex = 4;
                        }
                    }
                    else
                    {
                        key.User.Status = (short)TestorUserStatus.InetUser;
                        string userLogin = key.User.Login;
                        dataContext.ActivationKeys.DeleteOnSubmit(key);
                        dataContext.SubmitChanges();
                        FormsAuthentication.RedirectFromLoginPage(userLogin, false);
                    }
                }
                return;
            }
            else if (Request["Restore"] != null)
            {
                if (!this.IsPostBack)
                {
                    MultiView1.ActiveViewIndex       = 2;
                    this.Session["CaptchaImageText"] = GenerateRandomCode();
                }
                LabelRestoreError.Visible = false;
                return;
            }
            else
            {
                if (!this.IsPostBack)
                {
                    this.Session["CaptchaImageText"] = GenerateRandomCode();
                }
                aspErrorMessage.Visible = false;
            }
        }
コード例 #26
0
ファイル: Register.aspx.cs プロジェクト: clgray/Locator
        protected void Btn_Reg_Click(object sender, EventArgs e)
        {
            int groupId = 0;

            TextBoxPassword.Attributes["Value"]       = TextBoxPassword.Text;
            TextBoxSecondPassword.Attributes["Value"] = TextBoxSecondPassword.Text;
            if (LocalUser.IsIntranet)
            {
                if (ViewState["SelectedNode"] != null)
                {
                    int.TryParse((string)ViewState["SelectedNode"], out groupId);
                }

                if (groupId == 0 || ViewState["SelectedNode"] == null)
                {
                    aspErrorMessage.Visible = true;
                    aspErrorMessage.Text    = "Выберите группу (Факультет -> Кафедра -> Группа).";
                    return;
                }
            }
            if (TextBoxCaptcha.Text.ToLower() != this.Session["CaptchaImageText"].ToString().ToLower())
            {
                aspErrorMessage.Visible          = true;
                aspErrorMessage.Text             = "Введён неправильный секретный код";
                TextBoxCaptcha.Text              = String.Empty;
                this.Session["CaptchaImageText"] = GenerateRandomCode();
                return;
            }
            else
            {
                TextBoxCaptcha.Text = String.Empty;
                this.Session["CaptchaImageText"] = GenerateRandomCode();
                aspErrorMessage.Visible          = false;
            }
            if (TextBoxLogin.Text.Trim().Contains(' ') || TextBoxPassword.Text.Contains(' '))
            {
                aspErrorMessage.Visible = true;
                aspErrorMessage.Text    = "Логин и пароль не могут содержать пробелы";
                return;
            }
            if (TextBoxPassword.Text != TextBoxSecondPassword.Text)
            {
                aspErrorMessage.Visible = true;
                aspErrorMessage.Text    = "Пароли не совпадают";
                return;
            }
            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                string eMail = TextBoxEmail.Text.Trim().ToLower();
                if (!String.IsNullOrEmpty(eMail) && dataContext.Users.Where(c => c.Email == eMail).Count() > 0)
                {
                    aspErrorMessage.Visible = true;
                    aspErrorMessage.Text    = "Данный e-mail уже используется";
                    return;
                }
                if (!LocalUser.IsIntranet)
                {
                    if (TextBoxGroup.Text.Trim() != String.Empty)
                    {
                        groupId = dataContext.GetGroupIdByCode(TextBoxGroup.Text.Trim());
                        if (groupId == 0)
                        {
                            aspErrorMessage.Visible = true;
                            aspErrorMessage.Text    = "Неверный код группы";
                            return;
                        }
                    }
                }
                TestorTreeItem[] groups = new TestorTreeItem[] { };
                if (groupId != 0)
                {
                    TestorTreeItem group = new TestorTreeItem(groupId, 0, String.Empty, TestorItemType.Group, new TestorTreeItem[] { });
                    groups = new TestorTreeItem[] { group };
                }
                string password = TextBoxPassword.Text.Trim();
                if (String.IsNullOrEmpty(password))
                {
                    password = "******";
                }
                TestorCoreUser user = new TestorCoreUser()
                {
                    LastName   = TextBoxLastName.Text.Trim(),
                    FirstName  = TextBoxName.Text.Trim(),
                    SecondName = TextBoxSecondName.Text.Trim(),
                    Password   = password,
                    Sex        = DropDownListGender.SelectedIndex == 0 ? true : false,
                    UserGroups = groups,
                    UserRole   = TestorUserRole.Student,
                    Status     = LocalUser.IsIntranet ? TestorUserStatus.LocalNetUser : TestorUserStatus.NotActivated,
                    StudNumber = TextBoxStudNumber.Text.Trim()
                };
                if (LocalUser.IsIntranet)
                {
                    user.Login       = Guid.NewGuid().ToString();
                    user.IsLocalUser = true;
                    user.Email       = String.Format("{0}@{1}.testor.ru", user.Login, Guid.NewGuid().ToString());
                }
                else
                {
                    user.Login = TextBoxLogin.Text.Trim();
                    user.Email = TextBoxEmail.Text.Trim().ToLower();
                }
                try
                {
                    TestorCoreUser coreUser = LocalUser.UserManagement.CreateUser(user);
                    ActivationKey  key      = new ActivationKey();
                    key.ActivationKey1 = Guid.NewGuid().ToString();
                    key.UserId         = coreUser.UserId;
                    dataContext.ActivationKeys.InsertOnSubmit(key);
                    if (LocalUser.IsIntranet)
                    {
                        dataContext.SubmitChanges();
                        FormsAuthentication.RedirectFromLoginPage(coreUser.Login, false);
                        return;
                    }
                    else
                    {
                        dataContext.SubmitChanges();
                        SendActivationMail(coreUser.Email, key.ActivationKey1, coreUser.Login);
                    }
                }
                catch (Exception ex)
                {
                    aspErrorMessage.Visible = true;
                    aspErrorMessage.Text    = ex.Message;
                    return;
                }
                MultiView1.ActiveViewIndex = 1;
            }
        }
コード例 #27
0
        public TestorTreeItem[] SendTests(byte[] testorData, int folderId, int[] groupIds)
        {
            Debug.Assert(testorData != null);
            Debug.Assert(folderId >= 0);

            Provider.TestRoles(TestorUserRole.Administrator, TestorUserRole.Teacher, TestorUserRole.Laboratorian);

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                TestorData data = DataCompressor.DecompressData <TestorData>(testorData);

                //data.WriteXml("C:/locator.xml", System.Data.XmlWriteMode.IgnoreSchema);

                Dictionary <int, CoreTest> xTests = new Dictionary <int, CoreTest>();
                foreach (TestorData.CoreTestsRow coreTest in data.CoreTests)
                {
                    CoreTest test = new CoreTest();
                    test.TestKey      = coreTest.TestKey;
                    test.IsMasterTest = coreTest.IsMasterTest;
                    CreateCoreTest(coreTest, test);
                    xTests.Add(coreTest.TestId, test);
                    dataContext.CoreTests.InsertOnSubmit(test);
                    foreach (int groupId in groupIds)
                    {
                        TestGroup group = new TestGroup();
                        group.CoreTest = test;
                        group.GroupId  = groupId;
                        dataContext.TestGroups.InsertOnSubmit(group);
                    }
                    foreach (var coreQuest in coreTest.GetCoreQuestionsRows())
                    {
                        CoreQuestion quest = new CoreQuestion();
                        quest.CoreTest     = test;
                        quest.QuestionType = coreQuest.QuestionType;
                        quest.Question     = coreQuest.Question;
                        quest.QuestionMark = coreQuest.QuestionMark;
                        try
                        {
                            if (!Convert.IsDBNull(coreQuest.QuestionMetadata))
                            {
                                quest.QuestionMetadata = coreQuest.QuestionMetadata;
                            }
                        }
                        catch
                        {
                            quest.QuestionMetadata = null;
                        }
                        dataContext.CoreQuestions.InsertOnSubmit(quest);
                        foreach (var coreAnswer in coreQuest.GetCoreAnswersRows())
                        {
                            CoreAnswer answer = new CoreAnswer();
                            answer.CoreQuestion = quest;
                            answer.Answer       = coreAnswer.Answer;
                            answer.IsTrue       = coreAnswer.IsTrue;
                            try
                            {
                                if (!Convert.IsDBNull(coreAnswer.AnswerMetadata))
                                {
                                    answer.AnswerMetadata = coreAnswer.AnswerMetadata;
                                }
                            }
                            catch
                            {
                                answer.AnswerMetadata = null;
                            }
                            dataContext.CoreAnswers.InsertOnSubmit(answer);
                        }
                        foreach (var coreBlob in coreQuest.GetCoreBLOBsRows())
                        {
                            CoreBLOB blob = new CoreBLOB();
                            blob.CoreQuestion = quest;
                            blob.BLOBId       = coreBlob.BLOBId;
                            blob.BLOBContent  = coreBlob.BLOBContent;
                            dataContext.CoreBLOBs.InsertOnSubmit(blob);
                        }
                    }
                }
                foreach (var masterTest in data.CoreTests.Where(c => c.IsMasterTest == true))
                {
                    var parts = data.CoreMasterParts.Where(c => c.MasterTestId == masterTest.TestId);
                    var test  = xTests.Where(c => c.Value.TestKey == masterTest.TestKey).FirstOrDefault();
                    foreach (var part in parts)
                    {
                        CoreMasterPart masterPart = new CoreMasterPart();
                        masterPart.CoreTest1 = test.Value;
                        masterPart.CoreTest  = xTests.Where(
                            c => c.Key == part.PartTestId).FirstOrDefault().Value;
                        masterPart.QuestionsNumber = part.QuestionsNumber;
                        dataContext.CoreMasterParts.InsertOnSubmit(masterPart);
                    }
                }
                foreach (var coreReq in data.CoreRequirements)
                {
                    CoreRequirement req     = new CoreRequirement();
                    Guid            testKey = data.CoreTests.Where(c => c.TestId == coreReq.TestId).FirstOrDefault().TestKey;
                    Guid            reqKey  = data.CoreTests.Where(c => c.TestId == coreReq.Requirement).FirstOrDefault().TestKey;
                    req.CoreTest  = xTests.Where(c => c.Value.TestKey == testKey).FirstOrDefault().Value;
                    req.CoreTest1 = xTests.Where(c => c.Value.TestKey == reqKey).FirstOrDefault().Value;
                    dataContext.CoreRequirements.InsertOnSubmit(req);
                }
                try
                {
                    dataContext.SubmitChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                List <TestorTreeItem> retValue = new List <TestorTreeItem>();
                foreach (var test in xTests)
                {
                    CoreTest       coreTest = test.Value;
                    TestorItemType type     = TestorItemType.Test;
                    if (coreTest.IsMasterTest)
                    {
                        type = TestorItemType.MasterTest;
                    }
                    int            result = dataContext.AddTestTreeItem(GetId(folderId), (byte)type, coreTest.TestId, Provider.CurrentUser.UserId);
                    TestorTreeItem item   = new TestorTreeItem(result, coreTest.TestId,
                                                               coreTest.TestName, type, null);
                    retValue.Add(item);
                }
                return(retValue.ToArray());
            }
        }
コード例 #28
0
ファイル: Admin.aspx.cs プロジェクト: clgray/Locator
        protected void postButton_Click(object sender, EventArgs e)
        {
            var activeView = MultiViewMain.GetActiveView();

            if (activeView == ViewLogin)
            {
                LocalUser.SetPropertyValue(SystemProperties.SESSION_ALLOW_INTRANET, CheckBoxAllowIntranet.Checked ? SystemProperties.SESSION_TRUE : SystemProperties.SESSION_FALSE);
                LocalUser.SetPropertyValue(SystemProperties.SESSION_ALLOW_PUBLIC, CheckBoxAllowPublic.Checked ? SystemProperties.SESSION_TRUE : SystemProperties.SESSION_FALSE);

                LocalUser.SetPropertyValue(SystemProperties.SMTP_FROM, TextBoxFrom.Text.Trim());
                LocalUser.SetPropertyValue(SystemProperties.SMTP_SERVER, TextBoxSmtpServer.Text.Trim());
                LocalUser.SetPropertyValue(SystemProperties.SMTP_LOGIN, TextBoxSmtpLogin.Text.Trim());
                if (TextBoxSmtpPassword.Text.Trim() != String.Empty)
                {
                    LocalUser.SetPropertyValue(SystemProperties.SMTP_PASSWORD, TextBoxSmtpPassword.Text);
                }
                if (LocalUser.GetPropertyValue(SystemProperties.SESSION_LOCAL_NETWORKS) != TextBoxLocalNetworks.Text.Trim())
                {
                    LocalUser.SetPropertyValue(SystemProperties.SESSION_LOCAL_NETWORKS, TextBoxLocalNetworks.Text.Trim());
                }

                LocalUser.SetPropertyValue(SystemProperties.REGISTER_MAIL, TextBoxRegMailContext.Text.Trim());
                LocalUser.SetPropertyValue(SystemProperties.RESTORE_MAIL, TextBoxRegRestore.Text.Trim());
            }
            else if (activeView == ViewAnonym)
            {
                string value = String.Empty;
                if (radioButtonNone.Checked)
                {
                    value = "-1";
                }
                else if (radioButtonAll.Checked)
                {
                    value = "0";
                }
                else
                {
                    TestorTreeItem selFolder = (ViewState["SelectedFolder"] as TestorTreeItem);
                    if (selFolder == null)
                    {
                        value = "-1";
                    }
                    else
                    {
                        value = selFolder.ItemId.ToString();
                    }
                }
                LocalUser.HelperService.SetPropertyValue(SystemProperties.ANONYMOUS_POLICY, value);
            }
            else if (activeView == ViewUserDetails)
            {
                if (TextBoxPassword.Text != String.Empty || TextBoxSecondPassword.Text != String.Empty)
                {
                    if (TextBoxPassword.Text != TextBoxSecondPassword.Text)
                    {
                        aspErrorMessage.Text    = "Пароли не совпадают";
                        aspErrorMessage.Visible = true;
                        return;
                    }
                    else
                    {
                        using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
                        {
                            var user = dataContext.Users.Where(c => c.UserId == (int)GridViewUsers.SelectedValue).FirstOrDefault();
                            if (user == null || user.UserRole != (short)TestorUserRole.Student)
                            {
                                aspErrorMessage.Text    = "Ошибка. Не выбран пользователь";
                                aspErrorMessage.Visible = true;
                                return;
                            }
                            user.Password = TextBoxPassword.Text;
                            dataContext.SubmitChanges();
                        }
                    }
                }
            }
            changesIndicator.Text    = String.Format(" Изменения сохранены [{0}]", DateTime.Now.ToShortTimeString());
            changesIndicator.Visible = true;
        }
コード例 #29
0
        public StartTestParams StartTest(int testId)
        {
            Debug.Assert(testId > 0);

            StartTestParams retValue = new StartTestParams();

            using (DataClassesTestorCoreDataContext dataContext = new DataClassesTestorCoreDataContext(TestorSecurityProvider.ConnectionString))
            {
                var test = dataContext.CoreTests.Where(c => c.TestId == testId).First();
                if (!test.IsActive || test.IsDeleted)
                {
                    throw new Exception("Тест не активен");
                }
                if ((test.BeginTime > DateTime.Now && test.BeginTime != DateTime.MinValue) ||
                    (test.EndTime < DateTime.Now && test.EndTime != DateTime.MinValue))
                {
                    throw new Exception("Тест не активен");
                }
                int count = dataContext.TestSessions.Where(c => c.TestId == testId && c.UserId == Provider.CurrentUser.UserId).Count();
                if (test.PassagesNumber != 0 && count >= test.PassagesNumber)
                {
                    throw new Exception("Превышено максимальное количество попыток");
                }
                if (GetCurrentUserFailRequirements(testId).Count() > 0)
                {
                    throw new Exception("Предварительные тесты не пройдены");
                }
                TestSession newSession = new TestSession();
                newSession.UserId   = Provider.CurrentUser.UserId;
                newSession.TestId   = test.TestId;
                newSession.Score    = -1;
                newSession.IsPassed = false;

                List <TestSessionQuestion> sessionQuests = new List <TestSessionQuestion>();
                if (test.IsMasterTest)
                {
                    var masterParts = dataContext.CoreMasterParts.Where(c => c.MasterTestId == test.TestId).ToArray();
                    foreach (var masterPart in masterParts)
                    {
                        sessionQuests.AddRange(GetQuestsFromTest(newSession, null, masterPart, dataContext));
                    }
                }
                else
                {
                    sessionQuests.AddRange(GetQuestsFromTest(newSession, test, null, dataContext));
                }

                short i = 0;
                if (test.IsMasterTest && test.VariantsMode)
                {
                    foreach (var quest in sessionQuests.OrderBy(c => Guid.NewGuid()))
                    {
                        quest.QuestionIndex = i;
                        dataContext.TestSessionQuestions.InsertOnSubmit(quest);
                        i++;
                    }
                }
                else
                {
                    foreach (var quest in sessionQuests)
                    {
                        quest.QuestionIndex = i;
                        dataContext.TestSessionQuestions.InsertOnSubmit(quest);
                        i++;
                    }
                }

                newSession.UniqId   = Guid.NewGuid().ToString().Substring(0, 5);
                newSession.ClientIP = Provider.ClientIP;
                dataContext.TestSessions.InsertOnSubmit(newSession);
                newSession.StartTime = DateTime.Now;
                dataContext.SubmitChanges();
                InitStartTestParams(newSession, retValue, test.TimeLimit * 60, false, dataContext);
                newSession.MaxScore = retValue.MaxScore;
                dataContext.SubmitChanges();
            }
            return(retValue);
        }