Example #1
0
        public static int GetActiveReplyCount(int postID)
        {
            DidacheDb db = new DidacheDb();

            InteractionPost post = db.InteractionPosts.SingleOrDefault(p=>p.PostID == postID);

            if (post == null) {
                return 0;
            } else {
                return db.InteractionPosts.Count(p => p.ThreadID == post.ThreadID && p.IsDeleted == false);
            }
        }
Example #2
0
        public static Forum GetForum(int forumID, bool includeThreads)
        {
            Forum forum = null;

            if (includeThreads) {
                forum = new DidacheDb().Forums.Include("Threads").SingleOrDefault(f => f.ForumID == forumID);

                forum.Threads = forum.Threads.OrderByDescending(t => t.LastPostDate).ToList();

            } else {
                forum = new DidacheDb().Forums.SingleOrDefault(f => f.ForumID == forumID);
            }

            return forum;
        }
Example #3
0
        public static List<ActivityStreamItemBase> GetUsersItems()
        {
            var didache = new DidacheDb();

            // get the users courses first
            List<int> courseIDs = new List<int>();
            //var courses = Courses.GetUsersRunningCourses(CourseUserRole.Student);
            var courses = Courses.GetUsersCourses(CourseUserRole.Student);
            courses.RemoveAll(c => c.SessionID != 32);

            foreach (Course course in courses)
                courseIDs.Add(course.CourseID);

            return GetUsersItems(courseIDs);
        }
        public static void ApproveClassmateRequest(int requesterUserID, int targetUserID)
        {
            DidacheDb db = new DidacheDb();

            UserRelationship rel1 = db.UserRelationships
                .SingleOrDefault(ur => ur.RequesterUserID == requesterUserID && ur.TargetUserID == targetUserID);

            UserRelationship rel2 = db.UserRelationships
                .SingleOrDefault(ur => ur.RequesterUserID == targetUserID && ur.TargetUserID == requesterUserID);

            if (rel1 != null) {
                rel1.Status = (int) RelationshipStatus.Approved;
            }
            if (rel2 != null) {
                rel2.Status = (int) RelationshipStatus.Approved;
            }

            //db.SaveChanges();

            // add user actions
            UserAction ua = new UserAction() {
                SourceUserID = requesterUserID,
                TargetUserID = targetUserID,
                UserActionType = UserActionType.BecomeClassmates,
                ActionDate = DateTime.Now,
                GroupID =0,
                MessageID = 0,
                PostCommentID = 0,
                PostID = 0,
                Text = ""
            };
            db.UserActions.Add(ua);
            UserAction ua2 = new UserAction() {
                SourceUserID = targetUserID,
                TargetUserID = requesterUserID,
                UserActionType = UserActionType.BecomeClassmates,
                ActionDate = DateTime.Now,
                GroupID = 0,
                MessageID = 0,
                PostCommentID = 0,
                PostID = 0,
                Text = ""
            };
            db.UserActions.Add(ua2);
            db.SaveChanges();
        }
        public ActionResult AddFileGroup(int id)
        {
            var didacheDb = new DidacheDb();

            // get data
            var reader = new JsonFx.Json.JsonReader();
            dynamic json = reader.Read(HttpUtility.UrlDecode(Request.Form.ToString()));

            CourseFileGroup group = new CourseFileGroup();
            group.CourseID = id;
            group.SortOrder = 9999;
            group.Name = json.name;

            didacheDb.CourseFileGroups.Add(group);
            didacheDb.SaveChanges();

            return Json(new {groupid = group.GroupID, name=json.name, courseid= id});
        }
Example #6
0
        public static User GetUser(int id, bool flushCache = false)
        {
            string key = string.Format(_userIdKey, id);
            User user = (HttpContext.Current != null) ? HttpContext.Current.Cache[key] as User : null;

            if (user == null || flushCache) {
                user = new DidacheDb().Users.FirstOrDefault(u => u.UserID == id);

                if (user != null) {
                    HttpContext.Current.Cache.Add(key, user, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Default, null);

                    key = string.Format(_usernameKey, user.Username);
                    HttpContext.Current.Cache.Add(key, user, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Default, null);

                }
            }

            return user;
        }
Example #7
0
        public static List<CourseFileGroup> GetCourseFileGroups(int courseID)
        {
            List<CourseFileGroup> groups = new DidacheDb()
                .CourseFileGroups
                    .Include("CourseFileAssociations.CourseFile.User")
                .Where(g => g.CourseID == courseID)
                .OrderBy(g => g.SortOrder)
                .ToList();

            foreach (CourseFileGroup group in groups) {
                List<CourseFileAssociation> associations = group.CourseFileAssociations.ToList();

                associations.Sort(delegate(CourseFileAssociation a, CourseFileAssociation b) {
                    return a.SortOrder.CompareTo(b.SortOrder);
                });

                group.CourseFileAssociations = associations;
            }

            return groups;
        }
        public ActionResult CreatePost(string slug, Thread thread, FormCollection collection)
        {
            // add post to post id

            User profile = Users.GetLoggedInUser();
            DidacheDb db = new DidacheDb();

            // make thread
            thread.UserID = profile.UserID;
            thread.TotalReplies = 0;
            thread.TotalViews = 0;
            thread.ThreadDate = DateTime.Now;
            thread.UserName = profile.Username;
            thread.LastPostUserName = profile.Username;
            thread.LastPostUserID = profile.UserID;
            thread.LastPostID = 0;
            thread.LastPostDate = DateTime.Now;
            thread.LastPostSubject = collection["Subject"];

            db.Threads.Add(thread);
            db.SaveChanges();

            // add post to thread
            ForumPost post = new ForumPost();
            post.ThreadID = thread.ThreadID;
            post.ForumID = Int32.Parse(collection["ForumID"]);
            post.PostDate = DateTime.Now;
            post.UserID = profile.UserID;
            post.UserName = profile.FullName;
            post.ReplyToPostID = 0;
            post.Subject = collection["Subject"];
            post.PostContent = collection["PostContent"];
            post.PostContentFormatted = Forums.FormatPost(post.PostContent);

            db.ForumPosts.Add(post);
            db.SaveChanges();

            return RedirectToAction("Thread", new { slug = slug, id = thread.ThreadID });
        }
Example #9
0
        public static StudentFile SaveStudentFile(int userID, UserTaskData userData, HttpPostedFileBase file)
        {
            DidacheDb db = new DidacheDb();

            StudentFile studentFile = null;

            if (file.ContentLength > 0) {

                // setup data
                studentFile = new StudentFile();
                studentFile.UserID = userID;
                studentFile.UploadedDate = DateTime.Now;
                studentFile.UniqueID = Guid.NewGuid();
                studentFile.ContentType = file.ContentType;
                studentFile.Length = file.ContentLength;

                // setup physical file
                string extension = Path.GetExtension(file.FileName);
                string filenameWithoutExtension = Path.GetFileNameWithoutExtension(file.FileName);
                studentFile.Filename = Path.GetFileName(file.FileName);
                string savePath = Path.Combine(Settings.StudentFilesLocation, studentFile.UniqueID.ToString() + extension);

                // check file type
                /*
                if (!String.IsNullOrWhiteSpace(userData.Task.FileTypesAllowed)) {

                }
                */

                file.SaveAs(savePath);

                // save file info to DB
                db.StudentFiles.Add(studentFile);
                db.SaveChanges();
            }

            return studentFile;
        }
Example #10
0
        public static List<UserTaskData> GetUserTaskDataInUnit(int unitID, int userID, bool createFakeData)
        {
            DidacheDb db = new DidacheDb();
            List<UserTaskData> userTasks = null;

            if (createFakeData) {
                // for graders
                List<Task> tasks = db.Tasks.Where(t => t.UnitID == unitID).OrderBy(t => t.SortOrder).ToList();

                userTasks = new List<UserTaskData>();

                foreach (Task task in tasks) {
                    UserTaskData utd = new UserTaskData() {
                        TaskID = task.TaskID,
                        CourseID = task.CourseID,
                        UnitID = task.UnitID,
                        TaskCompletionStatus = TaskCompletionStatus.NotStarted,
                        Task = task
                    };

                    //utd.Task = task;

                    userTasks.Add(utd);
                }

            }
            else {
                userTasks = db.UserTasks
                    .Include("Task")
                    .Where(d => d.UserID == userID && d.Task.UnitID == unitID)
                    .OrderBy(d => d.Task.SortOrder)
                    .ToList();

            }

            return userTasks;
        }
        public static void AddClassmateRequest(int requesterUserID, int targetUserID)
        {
            DidacheDb db = new DidacheDb();

            UserRelationship rel = db.UserRelationships
                .SingleOrDefault(ur => ur.RequesterUserID == requesterUserID && ur.TargetUserID == targetUserID);

            if (rel == null) {

                // status from requester
                rel = new UserRelationship() {
                    RequesterUserID = requesterUserID,
                    TargetUserID = targetUserID,
                    RelationshipStatus = RelationshipStatus.PendingTargetApproval
                };

                db.UserRelationships.Add(rel);

                // status from target
                rel = new UserRelationship() {
                    RequesterUserID = targetUserID,
                    TargetUserID = requesterUserID,
                    RelationshipStatus = RelationshipStatus.PendingRequesterApproval
                };

                db.UserRelationships.Add(rel);

                db.SaveChanges();

                User requesterUser = Users.GetUser(requesterUserID);
                User targetUser = Users.GetUser(targetUserID);

                string classmateRequestBody = Emails.FormatEmail(Didache.Resources.emails.classmates_approvalrequest, null,null,null, requesterUser, targetUser, null, null, null);

                Emails.EnqueueEmail("*****@*****.**", targetUser.Email, "Classmate Request", classmateRequestBody, false);
            }
        }
Example #12
0
        private static List<ActivityStreamItemBase> GetUsersItems(List<int> courseIDs)
        {
            List<ActivityStreamItemBase> items = new List<ActivityStreamItemBase>();

            var didache = new DidacheDb();

            // discussion replies
            var posts = didache
                            .ForumPosts
                                .Include("User")
                                .Include("Thread.Forum.Course")
                            .Where(p => courseIDs.Contains(p.Thread.Forum.CourseID))
                            .OrderByDescending(p => p.PostDate)
                            .Take(20);
            foreach (ForumPost post in posts) {
                items.Add(new ForumReplyActivity() { User = post.User, ActivityDate = post.PostDate, Post = post });
            }

            // discussion replies
            var interactions = didache
                                .InteractionPosts
                                    .Include("User")
                                    .Include("Thread.Task.Course")
                                .Where(p => courseIDs.Contains(p.Thread.Task.CourseID))
                                .OrderByDescending(p => p.PostDate)
                                .Take(20);
            foreach (InteractionPost post in interactions) {
                items.Add(new InteractionActivity() { User = post.User, ActivityDate = post.PostDate, Post = post });
            }

            items.Sort(delegate(ActivityStreamItemBase a, ActivityStreamItemBase b) {
                return -a.ActivityDate.CompareTo(b.ActivityDate);
            });

            return items;
        }
        public static List<CarsCourse> GetUsersCourses(int userID)
        {
            DidacheDb db = new DidacheDb();

            return db.CarsCourses
                .Where(cu => cu.UserID == userID)
                .ToList()
                .OrderBy(cu => cu.Year)
                    .ThenBy(cu => cu.SessionOrder)
                    .ThenBy(cu => cu.CourseCode)
                .ToList();
        }
        public static List<User> GetRelationshipUsers(int userID, RelationshipStatus status)
        {
            DidacheDb db = new DidacheDb();

            return db.UserRelationships
                .Include("TargetUser")
                .Where(ur => ur.RequesterUserID == userID && ur.Status == (int)status)
                .Select(ur => ur.TargetUser)
                .ToList();
        }
        public static List<UserRelationship> GetUserRelationships(int userID, bool includeUserData)
        {
            DidacheDb db = new DidacheDb();

            if (includeUserData) {
                return db.UserRelationships
                    .Include("TargetUser")
                    .Where(ur => ur.RequesterUserID == userID)
                    .ToList();
            } else {
                return db.UserRelationships
                    .Where(ur => ur.RequesterUserID == userID)
                    .ToList();
            }
        }
Example #16
0
        public static bool IsAdministratorFacultyOrFacilitator(int userID)
        {
            DidacheDb db = new DidacheDb();

            User user = db.Users.Find(userID);

            if (user == null)
                return false;

            return
                    System.Web.Security.Roles.IsUserInRole(user.Username, UserRoles.Administrator) ||
                    System.Web.Security.Roles.IsUserInRole(user.Username, UserRoles.Facilitator) ||
                    System.Web.Security.Roles.IsUserInRole(user.Username, UserRoles.Faculty);
        }
        public static List<UserRelationship> GetRelationshipStatuses(int userID, List<User> foundUsers)
        {
            // convert the search data into user relationshsips with status == none
            List<UserRelationship> searchRelationships = foundUsers
                        .Select(user =>
                            new UserRelationship() {
                                RelationshipStatus = RelationshipStatus.None,
                                RequesterUserID = userID,
                                TargetUserID = user.UserID,
                                TargetUser = user })
                        .ToList();

            // get real status data
            DidacheDb db = new DidacheDb();
            List<int> userIDs = foundUsers.Select(fu => fu.UserID).ToList();
            List<UserRelationship> statuses =
                                db.UserRelationships
                                    .Where(ur => ur.RequesterUserID == userID && userIDs.Contains(ur.TargetUserID))
                                    .ToList();

            // merge data
            foreach (UserRelationship realRelationship in statuses) {
                searchRelationships.Find(ur => ur.TargetUserID == realRelationship.TargetUserID).RelationshipStatus = realRelationship.RelationshipStatus;
            }

            return searchRelationships;
        }
Example #18
0
        public static void MakeUserPrivate(int userID)
        {
            DidacheDb db = new DidacheDb();

            User user = db.Users.Find(userID);

            if (user != null) {
                user.AllowClassmateRequests = false;

                user.AddressSecuritySetting = UserSecuritySetting.Private;
                user.BiographySecuritySetting = UserSecuritySetting.Private;
                user.BirthdateSecuritySetting = UserSecuritySetting.Private;
                user.ChildrenSecuritySetting = UserSecuritySetting.Private;
                user.EmailSecuritySetting = UserSecuritySetting.Private;
                user.PhoneSecuritySetting = UserSecuritySetting.Private;
                user.PictureSecuritySetting = UserSecuritySetting.Private;
                user.ScheduleSecuritySetting = UserSecuritySetting.Private;
                user.SpouseSecuritySetting = UserSecuritySetting.Private;

                db.SaveChanges();
            }
        }
        public static UserRelationship GetRelationshipStatus(int requesterUserID, int targetUserID)
        {
            DidacheDb db = new DidacheDb();

            UserRelationship rel = db.UserRelationships
                .SingleOrDefault(ur => ur.RequesterUserID == requesterUserID && ur.TargetUserID == targetUserID);

            if (rel == null) {
                return new UserRelationship() {
                    RequesterUserID =requesterUserID,
                    TargetUserID = targetUserID,
                    RelationshipStatus = RelationshipStatus.None
                };
            } else {
                return rel;
            }
        }
Example #20
0
        public static List<Course> GetUsersRunningCourses(int userID, CourseUserRole roleID)
        {
            string key = String.Format("courses-userrunning-{0}-{1}", userID, roleID);
            List<Course> courses = (HttpContext.Current != null) ? HttpContext.Current.Cache[key] as List<Course> : null;

            bool ignoreCache = true;

            if (courses == null || ignoreCache) {

                DateTime targetStartDate = DateTime.Now.AddDays(7);
                DateTime targetEndDate = DateTime.Now.AddDays(-7);

                var courseQuery = new DidacheDb().Courses.AsQueryable();

                // all the roles
                if (roleID == CourseUserRole.All) {

                    courseQuery = courseQuery.Where(c => c.CourseUsers.Any(cu => cu.UserID == userID) &&
                                                        c.StartDate <= targetStartDate &&
                                                        c.EndDate >= targetEndDate);
                } else {
                    courseQuery = courseQuery.Where(c => c.CourseUsers.Any(cu => cu.UserID == userID &&
                                                        cu.RoleID == (int)roleID) &&
                                                        c.StartDate <= targetStartDate &&
                                                        c.EndDate >= targetEndDate);
                }

                courses = courseQuery
                    .Distinct()
                    .OrderByDescending(c => c.StartDate)
                    .ToList();

                if (roleID == CourseUserRole.Student)
                    courses = courses.Where(c => c.IsActive).ToList();

                HttpContext.Current.Cache.Add(key, courses, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 3, 0), CacheItemPriority.Default, null);
            }

            return courses;
        }
Example #21
0
        public static bool IsUserInCourseRole(int courseID, int userID, CourseUserRole courseUserRole)
        {
            string key = string.Format("courserole-{0}-{1}-{2}", courseID, userID, courseUserRole);
            bool isInRole = false;

            if (System.Web.HttpContext.Current.Cache[key] != null) {
                isInRole = (bool)System.Web.HttpContext.Current.Cache[key];
            } else {
                isInRole = new DidacheDb().CourseUsers.Count(cu => cu.UserID == userID && cu.CourseID == courseID && cu.RoleID == (int)courseUserRole) > 0;
                System.Web.HttpContext.Current.Cache.Insert(key, isInRole, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
            }

            return isInRole;
        }
Example #22
0
        public static void DeleteCourse(int courseID)
        {
            var db = new DidacheDb();

            // files
            db.Database.ExecuteSqlCommand("DELETE FROM oe_CourseFileGroups_Files WHERE GroupID IN (SELECT GroupID FROM oe_CourseFileGroups WHERE CourseID = " + courseID + ");");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_CourseFileGroups WHERE CourseID = " + courseID + ";");

            // interactions
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Interactions_Posts WHERE TaskID IN (SELECT TaskID FROM oe_Courses_Tasks WHERE CourseID = " + courseID + ");");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Interactions_Threads WHERE TaskID IN (SELECT TaskID FROM oe_Courses_Tasks WHERE CourseID = " + courseID + ");");

            // forums
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Forums_Posts WHERE ForumID IN (SELECT ForumID FROM oe_Forums WHERE CourseID = " + courseID + ");");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Forums_Threads WHERE ForumID IN (SELECT ForumID FROM oe_Forums WHERE CourseID = " + courseID + ");");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Forums WHERE CourseID = " + courseID + ";");

            // main stuff
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses WHERE CourseID = " + courseID + ";");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses_Units WHERE CourseID = " + courseID + ";");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses_Tasks WHERE CourseID = " + courseID + ";");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses_Tasks_UserData WHERE CourseID = " + courseID + ";");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses_UserGroups WHERE CourseID = " + courseID + ";");
            db.Database.ExecuteSqlCommand("DELETE FROM oe_Courses_Users WHERE CourseID = " + courseID + ";");

            db.Database.ExecuteSqlCommand("DELETE FROM oe_UnitSurveys WHERE CourseID = " + courseID + ";");
        }
Example #23
0
        public static Course GetCourse(int courseID, bool useCache)
        {
            string key = string.Format(_courseById, courseID);
            Course course = (HttpContext.Current != null) ? HttpContext.Current.Cache[key] as Course : null;

            if (course == null || !useCache) {
                course = new DidacheDb().Courses.SingleOrDefault(c => c.CourseID == courseID);

                if (course != null)
                    HttpContext.Current.Cache.Add(key, course, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Default, null);
            }

            return course;
        }
        public ActionResult UpdateUnitSorting(int id)
        {
            var didacheDb = new DidacheDb();

            string data = HttpUtility.UrlDecode(Request.Form.ToString());

            //dynamic newValue = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.>(data);
            var reader = new JsonFx.Json.JsonReader();
            dynamic output = reader.Read(data);

            foreach (var unitInfo in output) {

                // get and update the unit
                Unit unit = didacheDb.Units.Find(unitInfo.unitid);
                unit.SortOrder = unitInfo.sortorder;

                foreach (var taskInfo in unitInfo.tasks) {
                    // get and update the task
                    Task task = didacheDb.Tasks.Find(taskInfo.taskid);
                    task.SortOrder = taskInfo.sortorder;

                }

            }

            string errorMessage = "";
            bool success = false;

            try {
                didacheDb.SaveChanges();
                success = true;
            } catch {
                var entries = didacheDb.GetValidationErrors();
                foreach (var entry in entries) {
                    errorMessage += "[" + entry.Entry.Entity.ToString() + "]\n";
                    foreach (var error in entry.ValidationErrors) {
                        errorMessage += error.PropertyName + " = " + error.ErrorMessage + "; ";
                    }
                }
            }

            return Json(new { success = success, errorMessage = errorMessage});
        }
Example #25
0
        public static Course GetCourseBySlug(string slug, bool useCache)
        {
            string key = string.Format(_courseBySlug, slug);
            Course course = (HttpContext.Current != null) ? HttpContext.Current.Cache[key] as Course : null;

            if (course == null || !useCache) {
                //string[] parts = slug.Split(new char[] { '-' });
                //string sessionInfo = parts[0].Trim().ToUpper();
                //string courseCode = parts[1].Trim().ToUpper();

                int firstDash = slug.IndexOf("-");
                string sessionInfo = slug.Substring(0, firstDash);
                string courseCode = slug.Substring(firstDash+1);

                var db = new DidacheDb();

                //Session session = db.Sessions.SingleOrDefault(s => s.SessionCode == sessionCode);
                //Course course = session.Courses.SingleOrDefault(c => c.CourseCode + c.Section == courseCode);

                int sessionYear = 0;
                string sessionCode = "";

                if (sessionInfo.Length >= 5) {
                    if (Int32.TryParse(sessionInfo.Substring(sessionInfo.Length - 4), out sessionYear)) {
                        sessionCode = sessionInfo.Substring(0, sessionInfo.Length - 4);
                    }
                } else {
                    throw new Exception("Your session is invalid bro");
                }

                course = db.Courses
                                    .Include("Session")
                                    .Include("Campus")
                                    .SingleOrDefault(c => c.CourseCode + c.Section == courseCode && c.Session.SessionCode == sessionCode && c.Session.SessionYear == sessionYear);

                if (course != null)
                    HttpContext.Current.Cache.Add(key, course, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Default, null);
            }

            return course;
        }
Example #26
0
        public static Course CloneCourse(int courseID, int sessionID, DateTime startDate, string courseCode, string section)
        {
            DidacheDb db = new DidacheDb();

            Course oldCourse = db.Courses
                                                .Include("Units.Tasks")
                                                .Include("CourseFileGroups.CourseFileAssociations")
                                                .SingleOrDefault(c => c.CourseID == courseID);

            int daysToShift = (startDate - oldCourse.StartDate).Days;

            Course newCourse = new Course() {
                SessionID = sessionID,
                CampusID = oldCourse.CampusID,
                IsActive = oldCourse.IsActive,
                CourseCode = !String.IsNullOrWhiteSpace(courseCode) ? courseCode : oldCourse.CourseCode,
                Name = oldCourse.Name,
                Section = !String.IsNullOrWhiteSpace(section) ? section : oldCourse.Section,
                StartDate = oldCourse.StartDate.AddDays(daysToShift),
                EndDate = oldCourse.EndDate.AddDays(daysToShift),
                Description = oldCourse.Description
            };

            db.Courses.Add(newCourse);
            db.SaveChanges();

            /*
            } catch (DbEntityValidationException dbEx) {
                string errors = "";

                foreach (var validationErrors in dbEx.EntityValidationErrors) {
                    foreach (var validationError in validationErrors.ValidationErrors) {
                        //System.Web.HttpContext.Current.Trace.Warn("Property: {0} Error: {1}", validationError.PropertyName, dbEx);
                        errors += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + "; ";
                    }
                }

                throw new Exception(errors);
            }
            */

            foreach (Unit oldUnit in oldCourse.Units) {
                Unit newUnit = new Unit() {
                    CourseID = newCourse.CourseID,
                    IsActive = oldUnit.IsActive,
                    SortOrder = oldUnit.SortOrder,
                    Name = oldUnit.Name,
                    StartDate = oldUnit.StartDate.AddDays(daysToShift),
                    EndDate = oldUnit.EndDate.AddDays(daysToShift),
                    Instructions = oldUnit.Instructions
                };

                db.Units.Add(newUnit);
                db.SaveChanges();

                Dictionary<int, int> taskMap = new Dictionary<int, int>();
                List<Task> newTasks = new List<Task>();

                foreach (Task oldTask in oldUnit.Tasks) {
                    Task newTask = new Task() {
                        CourseID = newUnit.CourseID,
                        UnitID = newUnit.UnitID,
                        IsActive = oldTask.IsActive,
                        SortOrder = oldTask.SortOrder,
                        Name = oldTask.Name,
                        DueDate = null,
                        FileTypesAllowed = oldTask.FileTypesAllowed,
                        InstructionsAvailableDate = null,
                        IsSkippable = oldTask.IsSkippable,
                        Priority = oldTask.Priority,
                        RelatedTaskID = oldTask.RelatedTaskID,
                        SubmissionAvailableDate = null,
                        TaskID = oldTask.TaskID,
                        TaskTypeName = oldTask.TaskTypeName,
                        Instructions = oldTask.Instructions,
                        CustomAttributes = oldTask.CustomAttributes
                    };

                    if (oldTask.DueDate.HasValue)
                        newTask.DueDate = oldTask.DueDate.Value.AddDays(daysToShift);

                    if (oldTask.SubmissionAvailableDate.HasValue)
                        newTask.SubmissionAvailableDate = oldTask.SubmissionAvailableDate.Value.AddDays(daysToShift);

                    if (oldTask.InstructionsAvailableDate.HasValue)
                        newTask.InstructionsAvailableDate = oldTask.InstructionsAvailableDate.Value.AddDays(daysToShift);

                    db.Tasks.Add(newTask);

                    db.SaveChanges();

                    // store to remap the tasks below
                    newTasks.Add(newTask);
                    taskMap.Add(oldTask.TaskID, newTask.TaskID);
                }

                // go back and remap the related tasks
                List<int> newTaskIds = taskMap.Values.ToList();

                foreach(Task newTask in newTasks) {
                    if (newTask.RelatedTaskID > 0 && taskMap.ContainsKey(newTask.RelatedTaskID)) {
                        newTask.RelatedTaskID = taskMap[newTask.RelatedTaskID];
                    }
                }

                db.SaveChanges();
            }

            // FILES
            foreach (CourseFileGroup oldGroup in oldCourse.CourseFileGroups) {
                CourseFileGroup newGroup = new CourseFileGroup() {
                    CourseID = newCourse.CourseID,
                    Name = oldGroup.Name,
                    SortOrder = oldGroup.SortOrder
                };

                db.CourseFileGroups.Add(newGroup);
                db.SaveChanges();

                foreach (CourseFileAssociation oldFile in oldGroup.CourseFileAssociations) {
                    CourseFileAssociation newFile = new CourseFileAssociation() {
                        GroupID = newGroup.GroupID,
                        FileID = oldFile.FileID,
                        DateAdded = newCourse.StartDate,
                        IsActive = oldFile.IsActive,
                        SortOrder = oldFile.SortOrder
                    };

                    db.CourseFileAssociations.Add(newFile);
                }

                db.SaveChanges();

            }

            return newCourse;
        }
Example #27
0
        /*
        public static CourseUserGroup GetCoursesInGroup(int userID) {
            CourseUserGroup group = new DidacheDb().CourseUserGroups
                .Where(cu => cu.GroupID == groupID)
                .ToList();

            return users;
        }
         **/
        public static List<Unit> GetCourseUnitsWithTasks(int courseID)
        {
            List<Unit> units = new DidacheDb().Units
                .Include("Tasks")
                .Where(u => u.CourseID == courseID)
                .OrderBy(u => u.SortOrder)
                .ToList();

            foreach (Unit unit in units) {
                unit.Tasks = unit.Tasks.ToList().OrderBy(t => t.SortOrder).ToList();
            }

            return units;
        }
Example #28
0
        public static List<CourseUser> GetUsersInGroup(int groupID)
        {
            List<CourseUser> users = new DidacheDb().CourseUsers
                .Include("User")
                .Where(cu => cu.GroupID == groupID)
                .ToList();

            return users;
        }
        public ActionResult UpdateUserGroupSorting(int id)
        {
            var didacheDb = new DidacheDb();

            string data = HttpUtility.UrlDecode(Request.Form.ToString());

            //dynamic newValue = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.>(data);
            var reader = new JsonFx.Json.JsonReader();
            dynamic output = reader.Read(data);

            // get groups
            List<CourseUserGroup> groups = db.CourseUserGroups.Where(cfg => cfg.CourseID == id).ToList();
            List<int> groupIDs = groups.Select(cfg => cfg.GroupID).ToList();

            // get files
            List<CourseUser> courseUsers = db.CourseUsers.Where(cu => groupIDs.Contains(cu.GroupID)).ToList();

            foreach (var groupInfo in output) {
                CourseUserGroup userGroup = groups.SingleOrDefault(cug => cug.GroupID == groupInfo.groupid);

                foreach (var userInfo in groupInfo.users) {
                    CourseUser courseUser = courseUsers.SingleOrDefault(cu => cu.UserID == userInfo.userid);

                    // has the group changed?
                    if (courseUser.GroupID != userGroup.GroupID) {

                        // create a new one with the new group
                        CourseUser newCourseFile = new CourseUser() {
                            UserID = courseUser.UserID,
                            GroupID = userGroup.GroupID,
                            RoleID = (int)CourseUserRole.Student
                        };

                        db.CourseUsers.Remove(courseUser);
                        db.CourseUsers.Add(newCourseFile);

                    }
                    else {
                        // do nothing since we don't care about the order
                    }

                }
            }
            db.SaveChanges();

            /*
            foreach (var groupInfo in output) {

                // get and update the group
                CourseFileGroup fileGroup = didacheDb.CourseFileGroups.Find(groupInfo.groupid);
                fileGroup.SortOrder = groupInfo.sortorder;
                //fileGroup.Name = groupInfo.name;

                // TEST 2: get all existing, update, remove missing

                // get exsiting files
                List<CourseFileAssociation> courseFiles = didacheDb.CourseFileAssociations.Where(cfa => cfa.GroupID == fileGroup.GroupID).ToList();

                foreach (var fileInfo in groupInfo.files) {
                    // find the file
                    CourseFileAssociation cfa = courseFiles.Find(c => c.FileID == fileInfo.fileid);
                    if (cfa != null) {
                        // update
                        cfa.SortOrder = fileInfo.sortorder;
                        // add to change list
                        //changedFiles.Add(cfa);
                        courseFiles.Remove(cfa);
                    } else {
                        cfa = new CourseFileAssociation();
                        cfa.GroupID = fileGroup.GroupID;
                        cfa.FileID = fileInfo.fileid;
                        cfa.SortOrder = fileInfo.sortorder;
                        didacheDb.CourseFileAssociations.Add(cfa);
                    }
                }

                // remove all remaining files
                foreach (CourseFileAssociation notUpdated in courseFiles) {
                    didacheDb.CourseFileAssociations.Remove(notUpdated);
                }

            }
            */

            didacheDb.SaveChanges();

            // need to deserialize this and update all the groups and files

            return Json(new { success = true });
        }
Example #30
0
        public static List<CourseUserGroup> GetCourseUserGroups(int courseID)
        {
            List<CourseUserGroup> userGroups = new DidacheDb().CourseUserGroups
                .Include("Students.User")
                //.Include("Facilitator")
                .Where(g => g.CourseID == courseID)
                .ToList();

            foreach (CourseUserGroup group in userGroups) {
                List<CourseUser> users = group.Students.ToList();
                users.Sort(delegate(CourseUser a, CourseUser b) { return a.User.FormattedNameLastFirst.CompareTo(b.User.FormattedNameLastFirst); });
                group.Students = users;
            }

            return userGroups;
        }