示例#1
0
        public int UploadGradebookZip(byte[] zipData, GradebookFilePath gfp)
        {
            int filesFailedToLoadCount = 0;

            //clear existing data
            gfp.AllFiles().Delete();

            MemoryStream ms = new MemoryStream(zipData);

            ms.Position = 0;
            using (ZipFile zip = ZipFile.Read(ms))
            {
                //for each entry in zip, rename it to its FileName  and then extract it.(We rename it because zip files are named ZipFolder\Filename,
                //and this makes the file get added into a new folder named Zipfolder)
                for (int i = 0; i < zip.Count; i++)
                {
                    if (Path.GetExtension(zip[i].FileName) != ".csv")
                    {
                        filesFailedToLoadCount++;
                    }
                    else
                    {
                        zip[i].FileName = Path.GetFileName(zip[i].FileName);
                        zip[i].Extract(gfp.GetPath());
                    }
                }
            }
            return(filesFailedToLoadCount);
        }
示例#2
0
        public int UploadCourseGradebook(int courseID, byte[] zipData, string authToken)
        {
            int serviceResult = -1;

            //validate key
            if (!_authService.IsValidKey(authToken))
            {
                return(serviceResult);
            }

            //make sure the supplied user can modify the desired course
            UserProfile profile    = _authService.GetActiveUser(authToken);
            CourseUser  courseUser = (
                from cu in _db.CourseUsers
                where cu.UserProfileID == profile.ID
                &&
                cu.AbstractCourse is Course
                &&
                cu.AbstractCourseID == courseID
                select cu
                ).FirstOrDefault();

            if (courseUser == null || courseUser.AbstractRole.CanGrade == false)
            {
                //user can't grade that course
                return(serviceResult);
            }

            //upload the gradebook zip and return the result
            GradebookFilePath   gfp = Models.FileSystem.Directories.GetGradebook(courseUser.AbstractCourseID);
            GradebookController gc  = new GradebookController();

            try
            {
                serviceResult = gc.UploadGradebookZip(zipData, gfp, courseUser);
            }
            catch (Exception)
            {
            }
            return(serviceResult);
        }
示例#3
0
        public ActionResult Index(int courseId = -1, string gradebookName = null)
        {
            //default to user's default course
            if (courseId <= 0)
            {
                courseId = CurrentUser.DefaultCourseId;
            }
            Course currentCourse = Db.Courses.Where(c => c.Id == courseId).FirstOrDefault();
            CourseUserRelationship courseRelationship = Db.CourseUserRelationships
                                                        .Where(cur => cur.CourseId == currentCourse.Id)
                                                        .Where(cur => cur.UserId == CurrentUser.Id)
                                                        .FirstOrDefault();

            //Get the GradebookFilePath for current course
            FileSystem        fs  = new FileSystem();
            GradebookFilePath gfp = fs.Course(courseId).Gradebook();

            //get last upload time
            DirectoryInfo directoryInfo = new DirectoryInfo(gfp.GetPath());
            DateTime      lastUpload    = directoryInfo.LastWriteTime;

            //Generating list of Gradebook tabs
            List <string> TabNames = new List <string>();

            foreach (string temp in gfp.AllFiles())
            {
                TabNames.Add(Path.GetFileNameWithoutExtension(temp));
            }

            //Selecting which gradebook will be loaded. If gradebookName is null, then select the first tab
            bool gradeBookExists = true;

            if (gradebookName == null)
            {
                if (TabNames.Count > 0)
                {
                    gradebookName = TabNames[0];
                }
                else
                {
                    gradeBookExists = false;
                }
            }

            //If gradebook exists, set up certain viewbags
            ViewBag.GradeBookExists = gradeBookExists;
            if (gradeBookExists)
            {
                try
                {
                    SetUpViewBagForGradebook(courseRelationship, gradebookName);
                    ViewBag.SelectedTab = gradebookName;
                    ViewBag.TabNames    = TabNames;
                }
                catch (Exception)
                {
                    gradeBookExists         = false;
                    ViewBag.TabNames        = new List <string>();
                    ViewBag.SelectedTab     = "";
                    ViewBag.TableData       = new List <List <string> >();
                    ViewBag.GradeBookExists = false;
                }
            }


            //Setup viewbags based on usertype
            if (courseRelationship.Role == CourseRole.Coordinator)
            {
                //Setting instructor/Ta specific viewbags
                ViewBag.CanUpload = true;

                //TODO: Implement error messages
                ////Grabbing error message then wiping it.
                //if (Cache["UploadErrorMessage"] != null)
                //{
                //    ViewBag.UploadErrorMsg = Cache["UploadErrorMessage"];
                //    Cache["UploadErrorMessage"] = "";
                //}
            }
            else
            {
                //Setting student specific ViewBags
                ViewBag.CanUpload = false;
            }



            if (gradeBookExists)
            {
                ViewBag.LastUploadMessage = "Last updated " + lastUpload.ToShortDateString().ToString() + " " + lastUpload.ToShortTimeString().ToString() + "(UTC)";
            }
            else if (courseRelationship.Role == CourseRole.Coordinator)
            {
                //If user is an instructor and there is currnetly no gradebook, then change upload message
                ViewBag.LastUploadMessage = "Upload Gradebook File";

                //Generate additional upload fail messages.
            }

            ViewBag.CurrentCourseId = courseId;
            ViewBag.EnrolledCourses = Db.CourseUserRelationships.Where(cur => cur.UserId == CurrentUser.Id).Select(cur => cur.Course).ToList();

            return(View());
        }
示例#4
0
        /// <summary>
        /// Sets up ViewBags for the given gradebookName. The assumption made in this function is that the StudentID number is in
        /// column 0.
        /// </summary>
        /// <param name="gradebookName"></param>
        private void SetUpViewBagForGradebook(CourseUserRelationship courseUser, string gradebookName)
        {
            //Get the GradebookFilePath for current course, then the FileCollection for the given gradebookName
            FileSystem        fs        = new FileSystem();
            GradebookFilePath gfp       = fs.Course(courseUser.CourseId).Gradebook();
            FileCollection    gradebook = gfp.File(gradebookName + ".csv");;

            //Getting the filePath, which is the filename in the file collction
            string filePath = gradebook.FirstOrDefault();

            //Open the file as a FileStream. For this, we want to wrap it in a try/catch block, as others might be attempting to use this stream
            //at the same time. We'll allow it attempt to open the stream for up to maxTime.
            FileStream stream    = null;
            TimeSpan   interval  = new TimeSpan(0, 0, 0, 0, 50);
            TimeSpan   totalTime = new TimeSpan();
            TimeSpan   maxTime   = new TimeSpan(0, 0, 0, 4, 0); //4second max wait before giving up

            while (stream == null)
            {
                try
                {
                    //Get the stream related to the current file
                    stream = new FileStream(filePath, FileMode.Open);
                }
                catch (IOException ex)
                {
                    Thread.Sleep(interval);
                    totalTime += interval;

                    //if we've waited longer than maxTime, throw the original exception
                    if (totalTime > maxTime)
                    {
                        throw ex;
                    }
                }
            }

            //reading the file into a List of List of strings using CSVReader.
            List <List <string> > table     = new List <List <string> >();
            CsvReader             csvReader = new CsvReader(stream);

            table = csvReader.Parse();
            stream.Close(); //close the stream to allow others to access it.

            //If the user is NOT an instructor or TA, then only display them rows that match their UserProfileID.
            if (courseUser.Role == CourseRole.Student)
            {
                table = ParseStudentTable(courseUser, table);
            }
            else
            {
                List <int> globalRows    = new List <int>();
                List <int> hiddenColumns = new List <int>();
                //find which rows should be displayed as "globals"
                for (int i = 0; i < table.Count; i++)
                {
                    //Add global rows (denoted by a leading '#').
                    if (table[i][0].Length > 0 && table[i][0][0] == '#')
                    {
                        globalRows.Add(i);
                        for (int j = 0; j < table[i].Count; j++) //go through each cell in global row and check for hidden column values
                        {
                            if (table[i][j].Length > 2 && table[i][j][0] == '!' && table[i][j][1] == '!')
                            {
                                hiddenColumns.Add(j);
                            }
                        }
                    }
                }



                ViewBag.Instructor_ColumnsToHide = hiddenColumns;
                ViewBag.NameColumnIndex          = 1; //AC: ??
                ViewBag.GlobalRows = globalRows;
            }


            ViewBag.TableData = table;
        }
示例#5
0
        public ActionResult UploadGradebook(HttpPostedFileBase file, int courseId = -1)
        {
            //default to user's default course
            if (courseId <= 0)
            {
                courseId = CurrentUser.DefaultCourseId;
            }
            Course currentCourse = Db.Courses.Where(c => c.Id == courseId).FirstOrDefault();
            CourseUserRelationship courseRelationship = Db.CourseUserRelationships
                                                        .Where(cur => cur.CourseId == currentCourse.Id)
                                                        .Where(cur => cur.UserId == CurrentUser.Id)
                                                        .FirstOrDefault();

            //Get the GradebookFilePath for current course
            FileSystem        fs  = new FileSystem();
            GradebookFilePath gfp = fs.Course(courseId).Gradebook();

            //delete old items in gradebook
            int      filesInGradebookFolder = gfp.AllFiles().Count;
            int      filesDeleted           = 0;
            TimeSpan interval  = new TimeSpan(0, 0, 0, 0, 50);
            TimeSpan totalTime = new TimeSpan();
            TimeSpan maxTime   = new TimeSpan(0, 0, 0, 6, 0); //4second max wait before giving up

            while (filesInGradebookFolder != filesDeleted)
            {
                filesDeleted += gfp.AllFiles().Delete();
                if (filesInGradebookFolder != filesDeleted)
                {
                    Thread.Sleep(interval);
                    totalTime += interval;
                }
                if (totalTime > maxTime)
                {
                    throw new Exception("Failed to delete all gradebook files, try again later");;
                }
            }


            int filesFailedToLoadCount = 0; //integer used for error message

            //Add new item(s) based on file extension.
            if (file == null)
            {
                //No file. Meaning 1 file failed to load.
                filesFailedToLoadCount++;
            }
            else if (Path.GetExtension(file.FileName) == ".zip")
            {
                using (MemoryStream zipStream = new MemoryStream())
                {
                    file.InputStream.CopyTo(zipStream);
                    zipStream.Position      = 0;
                    filesFailedToLoadCount += UploadGradebookZip(zipStream.ToArray(), gfp);
                }
            }
            else if (Path.GetExtension(file.FileName) == ".csv")
            {
                //we have a .csv. Simply add it into the Gradebook directory
                gfp.AddFile(Path.GetFileName(file.FileName), file.InputStream);
            }
            else
            {
                //file wasnt csv or zip. Meaning 1 file failed to load.
                filesFailedToLoadCount++;
            }


            //Generate error message.
            if (filesFailedToLoadCount > 0)
            {
                if (filesFailedToLoadCount == 1)
                {
                    UserCache["UploadErrorMessage"] = filesFailedToLoadCount.ToString() + " file during upload was not of .csv file type, upload may have failed.";
                }
                else if (filesFailedToLoadCount > 1)
                {
                    UserCache["UploadErrorMessage"] = filesFailedToLoadCount.ToString() + " files during upload were not of .csv file type, upload may have failed.";
                }
            }

            return(RedirectToAction("Index"));
        }