public ActionResult DeleteTest(int id)
 {
     try
     {
         using (var db = new UsersContext())
         {
             var test = db.Tests.FirstOrDefault(t => t.TestId == id);
             db.Tests.Attach(test);
             var listQuestion = test.Questions.ToList();
             foreach (var question in listQuestion)
             {
                 if (question is QuestionWithVariants)
                 {
                     var listVariant = ((QuestionWithVariants) question).VariantAnswers.ToList();
                     foreach (var variantAnswer in listVariant)
                     {
                         db.VariantAnswers.Remove(variantAnswer);
                     }
                     db.QuestionWithVariants.Remove((QuestionWithVariants) question);
                 }
                 else
                 {
                     db.Questions.Remove(question);
                 }
             }
             db.Tests.Remove(test);
             db.SaveChanges();
         }
         return RedirectToAction("TeacherSpace", "Teacher");
     }
     catch (Exception)
     {
         return RedirectToAction("TeacherSpace", "Teacher");
     }
 }
 public ActionResult StartTest(int id)
 {
     using (var db = new UsersContext())
     {
         var test = db.Tests.FirstOrDefault(t => t.TestId == id);
         if (test == null) {return RedirectToAction("RolePermissions", "Home");}
         var userId = WebSecurity.GetUserId(User.Identity.Name);
         var actionInProgress = db.Actions.FirstOrDefault(a => a.User.UserId == userId && a.Status == 1);
         if (actionInProgress != null || test.Questions.Count == 0)
         {
             return RedirectToAction("Tests", "Test");
         }
         var action=new Action
         {
             User = db.UserProfiles.FirstOrDefault(u => u.UserId == userId),
             Test = test,
             Status = 1,   
             TestsInProgres = new List<TestInProgres>()
         };
         var listQuestion = test.Questions.OrderBy(q => q.Number).ToList();
         foreach (var question in listQuestion)
         {
             action.TestsInProgres.Add(new TestInProgres
             {
                 Action = action,
                 Question = question,
                 Submitted = false
             });
         }
         action.DateStart = DateTime.Now;
         db.Actions.Add(action);
         db.SaveChanges();
     }
     return RedirectToAction("TestInAction", "Test", new {number = 1});
 }
 public ActionResult FileUpload()
 {
     var userId = WebSecurity.GetUserId(User.Identity.Name);
     var directory = Server.MapPath("~/TestFiles/User="******"text/xml")
         {   
             var fileName = Path.GetFileName(file.FileName);
             var path = Path.Combine(directory, fileName);
             file.SaveAs(path);
             using (var db = new UsersContext())
             {
                 try
                 {
                     var test = XmlToTestParser.ParseFromXml(path);
                     test.User = db.UserProfiles.FirstOrDefault(u => u.UserId == userId);
                     test.PathFile = path;
                     db.Tests.Add(test);
                     db.SaveChanges();
                 }
                 catch (Exception)
                 {
                     return RedirectToAction("TeacherSpace", "Teacher");
                 }
             }
         }
     }
     return RedirectToAction("TeacherSpace", "Teacher");
 }
        public ViewResult Indexer(string sortOrder, string currentFilter, string searchString, int? page)
        {
            var db = new UsersContext();

            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            //  ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var students = from s in db.UserProfiles
                           select s;


            var users = db.UserProfiles.ToList();

            var allRAU = from e in users
                         select new { Name = e.UserName, Roless = Roles.GetRolesForUser(e.UserName).ElementAt(0) };

            if (!String.IsNullOrEmpty(searchString))
            {
                students = students.Where(s => s.UserName.ToUpper().Contains(searchString.ToUpper())
                                       || s.UserName.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    students = students.OrderByDescending(s => s.UserName);
                    break;
                default:
                    students = students.OrderBy(s => s.UserName);
                    break;
            }
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            return View(students.ToPagedList(pageNumber, pageSize));
        }
        public ActionResult TeacherSpace()
        {
            var testWrappers = new List<TestWrapper>();
            using (var db = new UsersContext())
            {
                var userId = WebSecurity.GetUserId(User.Identity.Name);
                var testList =
                    db.Tests.Where(test => test.User.UserId == userId)
                        .OrderByDescending(date => date.DateDownload)
                        .ToList();

                testWrappers.AddRange(testList.Select(test => new TestWrapper
                {
                    TestId = test.TestId, TestName = test.TestName, DateDownload = test.DateDownload, Order = test.Order
                }));
            }
            return View(testWrappers);
        }
        public ActionResult Tests()
        {
            var testWrappers = new List<TestInfoWrapper>();
            using (var db = new UsersContext())
            {
                var testInfoList =
                    db.Tests.OrderByDescending(date => date.DateDownload)
                        .ToList();

                testWrappers.AddRange(testInfoList.Select(test => new TestInfoWrapper
                {
                    TestId = test.TestId,
                    TestName = test.TestName,
                    CountQuestions = test.Questions.Count
                }));
            }
            return View(testWrappers);
        }
        public ActionResult Results()
        {
            var resultsWrapper = new List<ResultsWrapper>();
            using (var db = new UsersContext())
            {
                var userId = WebSecurity.GetUserId(User.Identity.Name);
                var resultList = db.TestsResults.Where(result=>result.User.UserId==userId)
                    .OrderByDescending(date => date.DatePassing).ToList();

                resultsWrapper.AddRange(resultList.Select(result => new ResultsWrapper
                {
                    TestResultId = result.TestResultId,
                    TestName = result.Test.TestName,
                    DatePassing = result.DatePassing,
                    Passed = result.Passed,
                    PercentTaken = result.PercentTaken
                }));
            }
            return View(resultsWrapper);
        }
 public ActionResult DetailsResult(int testResultId)
 {
     var detailsWrapper = new DetailsResultWrapper();
     using (var db = new UsersContext())
     {
         var userId = WebSecurity.GetUserId(User.Identity.Name);
         var testResult =
             db.TestsResults.FirstOrDefault(
                 result => result.User.UserId == userId && result.TestResultId == testResultId);
         if (testResult != null)
         {
             detailsWrapper.TestName = testResult.Test.TestName;
             detailsWrapper.PercentTaken = testResult.PercentTaken;
             detailsWrapper.Passed = testResult.Passed;
             
             var actionId = testResult.Action.ActionId;
             var historyList = db.TestHistory.Where(h => h.Action.ActionId == actionId).ToList();
             detailsWrapper.QuestionsList = GetQuestionDetailList(historyList, testResult);
         }
     }
     return View(detailsWrapper);
 }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

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

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
 public ActionResult TestInAction(int number)
 {
     using (var db = new UsersContext())
     {
         var userId = WebSecurity.GetUserId(User.Identity.Name);
         var action = db.Actions.FirstOrDefault(a => a.User.UserId == userId && a.Status == 1);
         if (action != null)
         {
             var currentQeustion =
                 action.TestsInProgres.FirstOrDefault(q => q.Question.Number==number);
             if (currentQeustion != null)
             {
                 if (currentQeustion.Question is QuestionWithVariants)
                 {
                     var questionInProgres = new QuestionInProgresWrapper(number, currentQeustion, action);
                     return View(questionInProgres);
                 }
             }
         }
     }
     ViewBag.WarningMessage = DataConst.WarningMessageForTest;
     return RedirectToAction("Tests", "Test");
 }
 private void SubbmitTest(int userId, TestInProgres currentQuestion, Action action, UsersContext db)
 {
         currentQuestion.Submitted = true;
         action.DatePassing = DateTime.Now;
         action.Status = 2;
         db.SaveChanges();
         CalculateResult(userId, action, db);
         CopyToHistory(action, db);
         RemoveFromProgres(action, db);
 }
 public ActionResult GoToQuestion(QuestionInProgresWrapper result, string submit)
 {
     using (var db = new UsersContext())
     {
         var userId = WebSecurity.GetUserId(User.Identity.Name);
         var action = db.Actions.FirstOrDefault(a => a.User.UserId == userId && a.Status == 1);
         var response = new ResponseAction(submit);
         if (action != null && response.CurrentNumber != null)
         {
             var currentQuestion =
                 action.TestsInProgres.FirstOrDefault(q => q.Question.Number == response.CurrentNumber);
             if (currentQuestion != null)
             {
                return CheckCurrentQuestion(result, response, userId, action, currentQuestion, db);
             }
         }
     }
     ViewBag.WarningMessage = DataConst.WarningMessageForTest;
     return RedirectToAction("TestInAction", "Test", new { number = 1 });
 }
        private void SaveResultOfRadioQuestion(QuestionInProgresWrapper result, TestInProgres currentQuestion, UsersContext db)
        {
            var userAnswer = "";

            for (var index = 0; index < ((QuestionWithVariants)currentQuestion.Question).VariantAnswers.Count; index++)
            {
                int number;
                if (Int32.TryParse(result.SelectedAnswer, out number))
                {
                    userAnswer += (number == index) ? "1" : "0";
                }
                else
                {
                    userAnswer += "0";
                }
            }
            currentQuestion.UserAnswer = userAnswer;
            currentQuestion.Submitted = true;
            db.SaveChanges();
        }
 private ActionResult CheckCurrentQuestion(QuestionInProgresWrapper result, ResponseAction response, int userId,
     Action action, TestInProgres currentQuestion, UsersContext db)
 {
     try
     {
         if (currentQuestion.Question.TestType == DataConst.CheckedType)
         {
             SaveResultOfCheckedQuestion(result, currentQuestion, db);
         }
         if (currentQuestion.Question.TestType == DataConst.RadioType)
         {
             SaveResultOfRadioQuestion(result, currentQuestion, db);
         }
        return ExecuteCommand(response, userId, action, currentQuestion, db);
     }
     catch (Exception)
     {
         ViewBag.WarningMessage = DataConst.WarningErrorMessage;
         return RedirectToAction("TestInAction", "Test", new { number = 1 });
     }
 }
 private void SaveResultOfCheckedQuestion(QuestionInProgresWrapper result, TestInProgres currentQuestion, UsersContext db)
 {
     var userAnswer = result.AnswerVariantList.Aggregate("",
                         (current, res) => current + (res.Selected ? "1" : "0"));
     currentQuestion.UserAnswer = userAnswer;
     currentQuestion.Submitted = true;
     db.SaveChanges();
 }
        private void RemoveFromProgres(Action action, UsersContext db)
        {
            db.Actions.Attach(action);

            var testsList= action.TestsInProgres.ToList();

            foreach (var testInProgres in testsList)
            {
                action.TestsInProgres.Remove(testInProgres);
                db.TestsInProgres.Remove(testInProgres);
            }
            db.SaveChanges(); 
        }
 private void CopyToHistory(Action action, UsersContext db)
 {
     foreach (var test in action.TestsInProgres)
     {
         var testToHistory = new TestHistory
         {
             Action = action,
             Number = test.Question.Number,
             Question = test.Question,
             UserAnswer = test.UserAnswer
         };
         db.TestHistory.Add(testToHistory);
         db.SaveChanges();
     }
 }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
 private ActionResult ExecuteCommand(ResponseAction response, int userId,
     Action action, TestInProgres currentQuestion, UsersContext db
     )
 {
     switch (response.Command)
     {
         case DataConst.Subbmit:
         {
             SubbmitTest(userId, currentQuestion, action, db);
             return RedirectToAction("Results", "Result");
         }
         case DataConst.Next:
         {
             if (response.CurrentNumber.HasValue)
             {
                 return RedirectToAction("TestInAction", "Test", new { number = response.CurrentNumber + 1});
             }
             break;
         }
         case DataConst.Prev:
         {
             if (response.CurrentNumber.HasValue)
             {
                 return RedirectToAction("TestInAction", "Test", new { number = response.CurrentNumber - 1 });
             }
             break;
         }
         case DataConst.GoTo:
         {
             if (response.GoTo.HasValue)
             {
                 return RedirectToAction("TestInAction", "Test", new { number = response.GoTo });
             }
             break;
         }
     }
     ViewBag.WarningMessage = DataConst.WarningErrorMessage;
     return RedirectToAction("TestInAction", "Test", new { number = 1 });
 }
        public ActionResult GetAllUsers()
        {
            var db = new UsersContext();

            var users = db.UserProfiles.ToList();
            //var users = Roles.GetUsersInRole("None");


            //List<string> roleset_to_find = new List<string>() { "Administrator", "Teacher", "User" };

            //List<string> membersFound = new List<string>();

            //foreach (string role in roleset_to_find)
            //{
            //    membersFound.AddRange(Roles.GetUsersInRole(role));
            //}

            var roles = new List<String[]>();

            foreach (var user in users)
            {

                roles.Add(Roles.GetRolesForUser(user.UserName));



            }
            ViewBag.Roles = roles;
            ViewBag.Error = "List is Empty!";
            // var users = Membership.GetAllUsers();
            return View(users);

        }
 private void CalculateResult(int userId, Action action, UsersContext db)
 {
     var testResult = new TestResults
     {
         User = db.UserProfiles.FirstOrDefault(u => u.UserId == userId),
         Action = action,
         Test = action.Test,
         DatePassing = action.DatePassing
     };
     double pointSum = 0;
     foreach (var test in action.TestsInProgres)
     {
         if (test.UserAnswer != null)
         {
             switch (test.Question.TestType)
             {
                 case DataConst.CheckedType:
                 {
                     pointSum += (CalculateChecked(test));
                     break;
                 }
                 case DataConst.RadioType:
                 {
                     pointSum += (CalculateRadio(test));
                     break;
                 }
             }
         }
     }
     testResult.PercentTaken = Convert.ToInt32((pointSum/action.TestsInProgres.Count)*100);
     testResult.Passed = testResult.PercentTaken >= DataConst.PercentLimit;
     db.TestsResults.Add(testResult);
     db.SaveChanges();
 }