public void CheckIfCourseNameIsChangedAfterCourseCreation()
        {
            Course course = new Course("math");
            course.Name = "financial math";

            Assert.AreEqual("financial math", course.Name, string.Format("Expected output after course name change financial math. Received {0}", course.Name));
        }
 public void CourseShouldThrowAnApplicationExceptionWhenTheSameStudentIsAddedMoreThanOnce()
 {
     Course testCourse = new Course("Test");
     Student testStudent = new Student("a");
     testCourse.AddStudent(testStudent);
     testCourse.AddStudent(testStudent);
 }
        public ActionResult AddLOsToCourse(Course course)
        {
            string stringOfLoIds = Request["selectedIds"];
            if (!stringOfLoIds.IsEmpty())
            {
                List<string> listOfLoIds = stringOfLoIds.Split(',').ToList();
                foreach (var id in listOfLoIds)
                {
                    var id1 = id;
                    var lo = _dbContext.LOs.Find(x => x.Id == ObjectId.Parse(id1)).SingleAsync().Result;
                    if (lo != null)
                    {
                        course.Duration += lo.Duration;
                        course.AddLo(lo.Id);
                    }
                }
            }

            ModelState.Clear();
            if (course.Id != ObjectId.Empty)
            {
                _logger.Trace("LO or LOs added to course during course editing");
                return View("EditCourse", course);
            }
            else
            {
                _logger.Trace("LO or LOs added to course during manual course creating");
                return View("ManualCourseCreating", course);
            }
        }
Example #4
0
        private static void Main()
        {
            try
            {
                Student pesho = new Student("Pesho Georgiev");
                Student gosho = new Student("Gosho Ivanov");
                Student misho = new Student("Misho Cekov");
                Student sasho = new Student("Sasho Kostov");

                Course telerikAcademy = new Course("Telerik Academy");
                Course webProgramming = new Course("Web Programming");

                webProgramming.AddStudent(sasho);

                telerikAcademy.AddStudent(pesho);
                telerikAcademy.AddStudent(gosho);
                telerikAcademy.AddStudent(misho);

                telerikAcademy.RemoveStudent(gosho);
                Console.WriteLine(gosho.ToString() + " was removed from course.");

                Console.WriteLine("Courses:");
                Console.WriteLine(telerikAcademy);

                School freeSchool = new School("School of Computer Sciences");
                freeSchool.AddCourse(webProgramming);
                freeSchool.AddCourse(telerikAcademy);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static void Main()
        {
            var streamReader = new StreamReader("../../students.txt");
            var multiDiuctionary = new OrderedMultiDictionary<Course, Student>(true);

            using (streamReader)
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    string[] parameters = line.Split(new char[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries);

                    string courseName = parameters[2];
                    var course = new Course(courseName);

                    string firstName = parameters[0];
                    string lastName = parameters[1];
                    var student = new Student(firstName, lastName);

                    multiDiuctionary.Add(course, student);

                    line = streamReader.ReadLine();
                }
            }

            PrintCourses(multiDiuctionary);
        }
 public void SchoolShouldAddCourseCorrectly()
 {
     var school = new School("Telerik Academy");
     var course = new Course("C#");
     school.AddCourse(course);
     Assert.AreSame(course, school.Courses.First());
 }
Example #7
0
 void btnAdd_Click(object sender, EventArgs e)
 {
     foreach (Control item in this.Controls)
     {
         TextBox tb = null;
         if (item is TextBox)
         {
             tb = item as TextBox;
             if (string.IsNullOrEmpty(tb.Text.Trim()))
             {
                 ShowMessage(tb.Tag + "不能为空");
                 return;
             }
         }
     }
     int credit = 0;
     bool b = Int32.TryParse(this.tbCcredit.Text.Trim(), out credit);
     if (!b)
     {
         ShowMessage("学分只能为数字,请重新输入!");
         return;
     }
     CourseMgrDataContext c = new CourseMgrDataContext();
     Course course = new Course();
     course.Cname = this.tbCname.Text.Trim();
     course.Cmajorname = this.tbCmajorname.Text.Trim();
     course.Cinfo = this.tbCinfo.Text.Trim();
     course.Cteacher = this.tbCteacher.Text.Trim();
     course.Ctime = this.tbCtime.Text.Trim();
     course.Ccredit = credit;
     c.Course.InsertOnSubmit(course);
     c.SubmitChanges();
     ShowMessage("添加新课程成功");
     this.DialogResult = DialogResult.OK;
 }
Example #8
0
		private void PatchInstructorsNotes(EdxCourse edxCourse, Course ulearnCourse, string olxPath)
		{
			var ulearnUnits = ulearnCourse.GetUnits().ToList();
			foreach (var chapter in edxCourse.CourseWithChapters.Chapters)
			{
				var chapterNote = ulearnCourse.InstructorNotes.FirstOrDefault(x => x.UnitName == chapter.DisplayName);
				if (chapterNote == null)
					continue;
				var unitIndex = ulearnUnits.IndexOf(chapterNote.UnitName);
				var displayName = "Заметки преподавателю";
				var sequentialId = string.Format("{0}-{1}-{2}", ulearnCourse.Id, unitIndex, "note-seq");
				var verticalId = string.Format("{0}-{1}-{2}", ulearnCourse.Id, unitIndex, "note-vert");
				var mdBlockId = string.Format("{0}-{1}-{2}", ulearnCourse.Id, unitIndex, "note-md");
				var sequentialNote = new Sequential(sequentialId, displayName,
					new[]
					{
						new Vertical(verticalId, displayName, new[] { new MdBlock(chapterNote.Markdown).ToEdxComponent(mdBlockId, displayName, ulearnCourse.GetDirectoryByUnitName(chapterNote.UnitName)) })
					}) { VisibleToStaffOnly = true };
				if (!File.Exists(string.Format("{0}/sequential/{1}.xml", olxPath, sequentialNote.UrlName)))
				{
					var sequentials = chapter.Sequentials.ToList();
					sequentials.Add(sequentialNote);
					new Chapter(chapter.UrlName, chapter.DisplayName, chapter.Start, sequentials.ToArray()).Save(olxPath);
				}
				sequentialNote.Save(olxPath);
			}
		}
 public void TestDismissStudent()
 {
     Course newCourse = new Course("Math");
     Student newStudent = new Student("Ivan", 1);
     newCourse.EnrollStudent(newStudent);
     newCourse.DismissStudent(newStudent);
 }
Example #10
0
        public IHttpActionResult PostCourse(Course course)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Courses.Add(course);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (CourseExists(course.Id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = course.Id }, course);
        }
Example #11
0
		private static Sequential[] UnitToSequentials(Course course, Config config, List<string> units, int unitIndex, string exerciseUrl, string solutionsUrl, Dictionary<string, string> videoGuids)
		{
			var result = new List<Sequential>
			{
				new Sequential(string.Format("{0}-{1}-{2}", course.Id, unitIndex, 0), units[unitIndex],
					course.Slides
						.Where(s => !config.IgnoredUlearnSlides.Contains(s.Id))
						.Where(y => y.Info.UnitName == units[unitIndex])
						.SelectMany(y => y.ToVerticals(course.Id, exerciseUrl, solutionsUrl, videoGuids, config.LtiId))
						.ToArray())
			};
			var note = course.FindInstructorNote(units[unitIndex]);
			var displayName = "Заметки преподавателю";
			var sequentialId = string.Format("{0}-{1}-{2}", course.Id, unitIndex, "note-seq");
			var verticalId = string.Format("{0}-{1}-{2}", course.Id, unitIndex, "note-vert");
			var mdBlockId = string.Format("{0}-{1}-{2}", course.Id, unitIndex, "note-md");
			if (note != null)
				result.Add(new Sequential(sequentialId, displayName,
					new[]
					{
						new Vertical(verticalId, displayName, new[] { new MdBlock(course.FindInstructorNote(units[unitIndex]).Markdown).ToEdxComponent(mdBlockId, displayName, course.GetDirectoryByUnitName(units[unitIndex])) })
					}) { VisibleToStaffOnly = "true" }
				);
			return result.ToArray();
		}
Example #12
0
        /// <summary>
        /// metodo que añade un curso nuevo
        /// </summary>
        /// <param name="c">curso a añadir</param>
        /// <returns>devulve el identificador del nuevo curso o -1 si no se puede añadir</returns>
        public static int Add(Course c)
        {
            try
            {
                if (c != null)
                {
                    using(SchoolEntities db = new SchoolEntities()) {
                        db.Course.Add(c);
                        db.SaveChanges();
                        return c.CourseID;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch (SqlException sqlex)
            {
                return -1;
            }
            catch (Exception ex)
            {

                return -1;
            }
        }
 public void CourseShouldThrowExceptionWhenExistingStudentAdded()
 {
     var course = new Course("HQC");
     Student student = new Student("Nikolay Kostov", 10000); 
     course.AddStudent(student);
     course.AddStudent(student);
 }
        /* 02. Write a console application that uses the data.*/
        /// <summary>
        /// Mains this instanse.
        /// </summary>
        public static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentSystemContext, Configuration>());
            using (var db = new StudentSystemContext())
            {
                var pesho = new Student { Name = "Pesho", Number = 666 };
                db.Students.Add(pesho);
                db.SaveChanges();

                var dbCourse = new Course
                {
                    Name = "Database Course",
                    Description = "Basic Database operations",
                    Materials = "http://telerikacademy.com/Courses/Courses/Details/98"
                };
                db.Courses.Add(dbCourse);
                db.SaveChanges();

                var course = db.Courses.First(c => c.Name == dbCourse.Name);
                var student = db.Students.First(s => s.Number == pesho.Number);

                var hw = new Homework
                {
                    Content = "Empty Homework",
                    TimeSent = DateTime.Now,
                    CourseId = course.CourseId,
                    StudentId = student.StudentID
                };
                db.Homeworks.Add(hw);
                db.SaveChanges();
            }

            ListStudents();
        }
        public ActionResult GetBatch(int departmentid, int campusid)
        {
            var id = _work.EnrollDep.Find(x => x.Depid == departmentid && x.Campid == campusid).Select(x => x.DepEnrolId);
            int enrollid = id.Single();

            IEnumerable<CourseToDep> subject = _work.CourseToDep.Find(x => x.DepEnrolId == enrollid);

            Course s = new Course();
            IEnumerable<EnrollBatch> b = _work.EnrollBatch.Find(x => x.DepEnrolId == enrollid);
            List<Course> listcourse = new List<Course>();
            foreach(var values in subject )
            {
                Course C = _work.Course.GetById(values.CId);
                listcourse.Add(C);
            }
            List<Batch> batch = new List<Batch>();
            foreach (var x in b)
            {
                batch.Add(x.batch);
            }

            // }

            var course= new SelectList(listcourse, "CId", "SubName");
            var batches = new SelectList(batch, "batch_id", "batch_name");
              object list= new
              {

              departs = batches,
              courses = course
              };

            return Json(list, JsonRequestBehavior.AllowGet);
        }
Example #16
0
        public void TestToAddStudent()
        {
            Course html = new Course("HTML");
            html.AddStudent(new Student("Peter", 10001));

            Assert.AreEqual(1, html.SetOfStudents.Count);
        }
Example #17
0
        public void TestToGiveWrongStudentNumberInRemoveStudentMethod()
        {
            Course html = new Course("HTML");
            int notExpected = html.SetOfStudents.Count;

            html.RemoveStudent(10003);
        }
Example #18
0
        public void TestSchoolCreation()
        {
            var student1 = new Student("Maria");
            var student2 = new Student("Petur");
            var student3 = new Student("Asen");
            var student4 = new Student("Ivanka");
            var student5 = new Student("John");
            var student6 = new Student("Elizabeth");

            var studentsSet = new List<Student> { student1, student2, student3, student4, student5, student6 };
            var studentsSet2 = new List<Student> { student2, student3, student4 };
            var studentsSet3 = new List<Student> { student1, student3, student5, student6 };
            var studentsSet4 = new List<Student> { student2, student4 };

            var course = new Course(studentsSet);
            var course2 = new Course(studentsSet2);
            var course3 = new Course(studentsSet3);
            var course4 = new Course(studentsSet4);

            var courseSet = new List<Course> { course, course2, course3, course4 };

            var newSchool = new School(studentsSet, courseSet);
            Assert.AreEqual(studentsSet.Count, newSchool.Students.Count);
            Assert.AreEqual(courseSet.Count, newSchool.Courses.Count);
        }
Example #19
0
 public void AddTheSameStudent_AddTheSameStudentInCourse_ShouldThrowInvalidOperationException()
 {
     var student = new Student("Telerik", 9);
     Course course = new Course();
     course.AddStudent(student);
     course.AddStudent(student);
 }
        public void EnsureCourseNumberCanNotAcceptValuesLessNonPositiveValues()
        {
            int number = -1;
            string name = "C#";

            Course course = new Course(name, number);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Title = "问答题管理";
        if (!IsPostBack)
        {
            if (Session["userID"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                string userId = Session["userID"].ToString();
                string userName = userService.GetUserName(userId);
                Label i1 = (Label)Page.Master.FindControl("labUser");
                i1.Text = userName;

                //展示绑定的数据并将它展示在下拉列表中
                ddlCourse.Items.Clear();
                Course course = new Course();
                Course[] list = singleSelectedService.ListCourse();

                for (int i = 0; i < list.Length; i++)
                {
                    ListItem item = new ListItem(list[i].DepartmentName.ToString(), list[i].DepartmentId.ToString());
                    ddlCourse.Items.Add(item);
                }

                string selectvalue = this.ddlCourse.SelectedValue;
                this.GridView1.DataSource = questionProblemService.GetQuestionProblem(selectvalue);
                this.GridView1.DataBind();
            }
        }
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            Course course = new Course();               //创建试卷科目对象
            if (course.IsCourseNameExist(txtName.Text.Trim()))
            {
                AjaxCommond ac = new AjaxCommond();
                ac.OpenDialogForButton((ImageButton)sender, "该名称已被占用!!!");
                txtName.Text = "";
            }
            else
            {
                course.Name = txtName.Text;                 //设置试卷科目对象属性
                if (course.InsertByProc())                  //调用添加试卷科目方法添加试卷科目
                {
                    lblMessage.Text = "成功添加该试卷科目!";
                    txtName.Text = "";

                }
                else
                {
                    lblMessage.Text = "添加该试卷科目失败!";
                }
            }

        }
    }
Example #23
0
    //**************************************
    //    
    public bool VerifyCompletion(Course c)
    {
        bool outcome = false;

        // Step through all TranscriptEntries, looking for one
        // which reflects a Section of the Course of interest.

        foreach ( TranscriptEntry te in TranscriptEntries ) {
          Section s = te.Section;

          if ( s.IsSectionOf(c) ) {
        // Ensure that the grade was high enough.

        if ( TranscriptEntry.PassingGrade(te.Grade) ) {
          outcome = true;

          // We've found one, so we can afford to
          // terminate the loop now.

          break;
        }
          }
        }

        return outcome;
    }
Example #24
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //do insert or update
            using (DefaultConnectionEF db = new DefaultConnectionEF())
            {
                Course objC = new Course();

                if (!String.IsNullOrEmpty(Request.QueryString["CourseID"]))
                {
                    Int32 CourseID = Convert.ToInt32(Request.QueryString["CourseID"]);
                    objC = (from c in db.Courses
                            where c.CourseID == CourseID
                            select c).FirstOrDefault();
                }

                //populate the course from the input form
                objC.Title = txtTitle.Text;
                objC.Credits = Convert.ToInt32(txtCredits.Text);
                objC.DepartmentID = Convert.ToInt32(ddlDepartment.SelectedValue);

                if (String.IsNullOrEmpty(Request.QueryString["CourseID"]))
                {
                    //add
                    db.Courses.Add(objC);
                }

                //save and redirect
                db.SaveChanges();
                Response.Redirect("courses.aspx");
            }
        }
Example #25
0
 public void Course_TestingStudentsList()
 {
     Course testCourse = new Course("Java");
     Student ivan = new Student("Ivan", 22222);
     testCourse.AddStudent(ivan);
     Assert.IsTrue(testCourse.Students.Contains(ivan));
 }
Example #26
0
 public void StudentLeavingCourseShouldNotThrowException()
 {
     Student student = new Student("Humpty Dumpty", 10000);
     Course course = new Course("Unit Testing");
     student.AttendCourse(course);
     student.LeaveCourse(course);
 }
 public void RemoveNonExistingCourseTest()
 {
     List<Course> courses = new List<Course>();
     School school = new School(courses);
     Course javaScript = new Course("JavaScript");
     school.RemoveCourse(javaScript);
 }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //Student s = new Student();
        //s.EnrolStudent((int)(gvCourse.SelectedValue), int.Parse(ddlNewStudents.SelectedValue), DateTime.Today.Year.ToString());
        //lblMessage.Text = "Student added";
        //gvClass.DataBind();
        //displayStudent();

        Course objCourse = new Course();

        //get information for enrolling student

        int studentID = int.Parse(ddlNewStudents.SelectedValue);

        int courseID = (int)gvCourse.SelectedValue;

        string year = DateTime.Now.Year.ToString();

        int numRowsAffected = objCourse.EnrolStudent(studentID, courseID, year);

        //display confirmation message
        if (numRowsAffected > 0)
        {
            lblMessage.Text = "New student added";
            lblMessage.CssClass = "confirmation";

        }
        else
        {
            lblMessage.Text = "Faild to add new student";
            lblMessage.CssClass = "error";
        }
    }
    //添加考试科目事件
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            Course course = new Course();               //创建考试科目对象
            //start:胡媛媛修改,去掉考试科目输入框两边的空格,加trim(),2010-4-29
            course.Name = txtName.Text.Trim();                 //设置考试科目对象属性

            //程军添加,添加考试科目,名称不能相同。2010-4-25
            DataBase db = new DataBase();
            string mySql = "select * from Course where Name ='" + txtName.Text.Trim() + "'";
            //end:胡媛媛修改,去掉考试科目输入框两边的空格,加trim(),2010-4-29
            if (db.GetRecord(mySql))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('课程章节重复!')</script>");
                this.txtName.Focus();
            }
            else
            {
               if (course.InsertByProc())                  //调用添加考试科目方法添加考试科目
              {
                  lblMessage.Text = "成功添加该章节科目!";
              }
              else
              {
                  lblMessage.Text = "添加该章节失败!";
              }
            }

            //程军添加,添加考试科目,名称不能相同。2010-4-25
        }
    }
Example #30
0
 public void School_AddCourseTest()
 {
     Course java = new Course("Java");
     School myTestSchool = new School();
     myTestSchool.AddCourse(java);
     Assert.AreEqual(java.CourseName, myTestSchool.Courses[0].CourseName);
 }
Example #31
0
        protected override void Seed(StudentMAnager.DAL.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
            var active      = true;
            var classId     = Guid.NewGuid().ToString();
            var studentId   = Guid.NewGuid().ToString();
            var courseId    = Guid.NewGuid().ToString();
            var gradeId     = Guid.NewGuid().ToString();
            var professorId = Guid.NewGuid().ToString();

            var sClass = new StudentClass
            {
                IsActive = active,
                Id       = classId,
                Name     = "Group A1"
            };
            var course = new Course
            {
                Year     = 1,
                IsActive = active,
                Id       = courseId,
                Name     = "Math",
                Credits  = 5,
                Semester = 2
            };
            var nine = new Grade
            {
                Id        = gradeId,
                DateNote  = DateTime.Today,
                Value     = 9.5,
                CourseId  = courseId,
                StudentId = studentId,
            };
            var professor = new Professor
            {
                IsActive  = active,
                FirstName = "Ionescu",
                LastName  = "Gabriel",
                Email     = "*****@*****.**",
                Id        = professorId,
                Country   = "Romania",
                BirthDay  = DateTime.Parse("01.01.1962"),
                Address1  = "Iasi",
                Address2  = "Salcamilor nr.25",
                City      = "Iasi",
                Courses   = new List <Course> {
                    course
                }
            };

            var student = new Student
            {
                Id             = studentId,
                StudentClassId = classId,
                IsActive       = active,
                FirstName      = "Popescu",
                LastName       = "Ionut",
                Email          = "*****@*****.**",
                Address1       = "Iasi",
                Address2       = "Merilor 25",
                BirthDay       = DateTime.Parse("01.01.1986"),
                City           = "Iasi",
                Country        = "Romania",
                Year           = 1,
                Courses        = new List <Course> {
                    course
                },
                Grades = new List <Grade> {
                    nine
                }
            };

            var classId1     = Guid.NewGuid().ToString();
            var studentId1   = Guid.NewGuid().ToString();
            var courseId1    = Guid.NewGuid().ToString();
            var gradeId1     = Guid.NewGuid().ToString();
            var professorId1 = Guid.NewGuid().ToString();

            var sClass1 = new StudentClass
            {
                IsActive = active,
                Id       = classId1,
                Name     = "Group B2"
            };
            var course1 = new Course
            {
                Year     = 1,
                IsActive = active,
                Id       = courseId1,
                Name     = "Web development",
                Credits  = 5,
                Semester = 2
            };
            var nine1 = new Grade
            {
                Id        = gradeId1,
                DateNote  = DateTime.Today,
                Value     = 9.5,
                CourseId  = courseId1,
                StudentId = studentId1,
            };
            var professor1 = new Professor
            {
                IsActive  = active,
                FirstName = "Sabin",
                LastName  = "Cornelus",
                Email     = "*****@*****.**",
                Id        = professorId1,
                Country   = "Romania",
                BirthDay  = DateTime.Parse("01.01.1988"),
                Address1  = "Iasi",
                Address2  = "Copou 65",
                City      = "Iasi",
                Courses   = new List <Course> {
                    course1
                }
            };

            var student1 = new Student
            {
                Id             = studentId1,
                StudentClassId = classId1,
                IsActive       = active,
                FirstName      = "Stan",
                LastName       = "Alex",
                Email          = "*****@*****.**",
                Address1       = "Iasi",
                Address2       = "Bazei 2.2.p",
                BirthDay       = DateTime.Parse("01.01.1995"),
                City           = "Iasi",
                Country        = "Romania",
                Year           = 1,
                Courses        = new List <Course> {
                    course1
                },
                Grades = new List <Grade> {
                    nine1
                }
            };


            context.Grades.AddOrUpdate(nine);
            context.Classes.AddOrUpdate(sClass);
            context.Courses.AddOrUpdate(course);
            context.Professors.AddOrUpdate(professor);
            context.Students.AddOrUpdate(student);


            context.Grades.AddOrUpdate(nine1);
            context.Classes.AddOrUpdate(sClass1);
            context.Courses.AddOrUpdate(course1);
            context.Professors.AddOrUpdate(professor1);
            context.Students.AddOrUpdate(student1);
        }
 public static bool UpdateCourse(Course c, int coId)
 {
     return(db.Courses.UpdateCourse(c, coId));
 }
 public static bool AddCourse(Course c)
 {
     return(db.Courses.AddCourse(c));
 }
Example #34
0
        public void JoinStudentNullInCourseTest()
        {
            Course course = CreateCourseTest();

            school.JoinStudentInCourse(null, course);
        }
Example #35
0
 public static double GetValueOfCourse(Course course)
 {
     return(Math.Ceiling(((double)course.DurationInMinutes / 60)) * 875);
 }
Example #36
0
        private async Task TryUpdateCourse(Course course, CourseUpdateOptions updateOptions, CourseExportResults results)
        {
            results.Info($"Downloading stepik course #{updateOptions.StepikCourseId}");
            var stepikCourse = await client.GetCourse(updateOptions.StepikCourseId).ConfigureAwait(false);

            results.StepikCourseTitle = stepikCourse.Title;

            results.Info($"Downloading stepik sections for it ({string.Join(", ", stepikCourse.SectionsIds)})");
            var stepikSections = new Dictionary <int, StepikApiSection>();

            // TODO (andgein): download multiple sections in one request
            foreach (var sectionId in stepikCourse.SectionsIds)
            {
                stepikSections[sectionId] = await client.GetSection(sectionId).ConfigureAwait(false);
            }

            var stepikUnitsIds = stepikSections.SelectMany(kvp => kvp.Value.UnitsIds).ToList();

            results.Info($"Downloading stepik units ({string.Join(", ", stepikUnitsIds)}) and lessons for them");
            var stepikUnits = new Dictionary <int, StepikApiUnit>();

            foreach (var unitId in stepikUnitsIds)
            {
                stepikUnits[unitId] = await client.GetUnit(unitId).ConfigureAwait(false);
            }

            var stepikLessonsIds = stepikUnits.Select(kvp => kvp.Value.LessonId);
            var stepikLessons    = new Dictionary <int, StepikApiLesson>();

            foreach (var lessonId in stepikLessonsIds)
            {
                stepikLessons[lessonId] = await client.GetLesson(lessonId).ConfigureAwait(false);
            }

            var sectionIndex = stepikCourse.SectionsIds.Count;

            foreach (var slideUpdateOptions in updateOptions.SlidesUpdateOptions)
            {
                var slideId = slideUpdateOptions.SlideId;
                var slide   = course.FindSlideById(slideId);
                if (slide == null)
                {
                    results.Error($"Unable to find slide {slideId}, continue without it");
                    continue;
                }

                results.Info($"Updating slide «{slide.Title}» with id {slide.Id}");
                var             stepId = slideUpdateOptions.InsertAfterStep;
                StepikApiLesson lesson;
                int             position;

                if (stepId != -1 && stepikLessons.Values.Any(l => l.StepsIds.Contains(stepId)))
                {
                    var lessonId = stepikLessons.FirstOrDefault(kvp => kvp.Value.StepsIds.Contains(stepId)).Key;
                    // Re-download lesson because it can be changed for a while
                    lesson = await client.GetLesson(lessonId).ConfigureAwait(false);

                    position = lesson.StepsIds.FindIndex(stepId);

                    results.Info($"Removing old steps created for this slide: {string.Join(", ", slideUpdateOptions.RemoveStepsIds)}");
                    await RemoveStepsFromLesson(lesson, slideUpdateOptions.RemoveStepsIds, results).ConfigureAwait(false);
                }
                else
                {
                    results.Info("Creating new stepik lesson for this slide");
                    lesson = await CreateLessonAndSectionForSlide(slide, stepikCourse, ++sectionIndex).ConfigureAwait(false);

                    position = 0;
                }

                results.Info($"Inserting steps for slide «{slide.Title}» into lesson {lesson.Id} on position {position}");
                await InsertSlideAsStepsInLesson(course, slide, lesson.Id.Value, position + 1, updateOptions, results);
            }
        }
        public static void EnsureSeedData(this SituatorContext context)
        {
            var empathy = context.Skills.Add(new Skill {
                Name = "Empathy"
            }).Entity;
            var reactivity = context.Skills.Add(new Skill {
                Name = "Reactivity"
            }).Entity;
            var aggressivity = context.Skills.Add(new Skill {
                Name = "Aggressivity"
            }).Entity;
            var leadership = context.Skills.Add(new Skill {
                Name = "Leadership"
            }).Entity;
            var energetic = context.Skills.Add(new Skill {
                Name = "Energetic"
            }).Entity;

            var course = new Course {
                Category = "Education", Description = "...", Title = "This is a Course"
            };

            var rootNode = new Node
            {
                IsRoot   = true,
                Text     = "Team building course",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 0
                    },
                    new Score {
                        Skill = reactivity, Point = 0
                    },
                    new Score {
                        Skill = aggressivity, Point = 0
                    },
                    new Score {
                        Skill = leadership, Point = 0
                    },
                    new Score {
                        Skill = energetic, Point = 0
                    }
                },
                PositionX = 350,
                PositionY = 50
            };

            var NodeA = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice: A",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 3
                    },
                    new Score {
                        Skill = reactivity, Point = 6
                    },
                    new Score {
                        Skill = aggressivity, Point = 4
                    },
                    new Score {
                        Skill = leadership, Point = 2
                    },
                    new Score {
                        Skill = energetic, Point = 1
                    }
                },
                PositionX = 200,
                PositionY = 200
            }).Entity;

            var NodeB = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice: B",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 4
                    },
                    new Score {
                        Skill = reactivity, Point = 7
                    },
                    new Score {
                        Skill = aggressivity, Point = 4
                    },
                    new Score {
                        Skill = leadership, Point = 2
                    },
                    new Score {
                        Skill = energetic, Point = 8
                    }
                },
                PositionX = 350,
                PositionY = 200
            }).Entity;

            var NodeC = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice C",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 0
                    },
                    new Score {
                        Skill = reactivity, Point = 5
                    },
                    new Score {
                        Skill = aggressivity, Point = 5
                    },
                    new Score {
                        Skill = leadership, Point = 4
                    },
                    new Score {
                        Skill = energetic, Point = 1
                    }
                },
                PositionX = 500,
                PositionY = 200
            }).Entity;

            var NodeAA = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice AA",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 1
                    },
                    new Score {
                        Skill = reactivity, Point = 4
                    },
                    new Score {
                        Skill = aggressivity, Point = 2
                    },
                    new Score {
                        Skill = leadership, Point = 2
                    },
                    new Score {
                        Skill = energetic, Point = 1
                    }
                },
                PositionX = 200,
                PositionY = 400
            }).Entity;

            var NodeAB = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice AB",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 8
                    },
                    new Score {
                        Skill = reactivity, Point = 0
                    },
                    new Score {
                        Skill = aggressivity, Point = 0
                    },
                    new Score {
                        Skill = leadership, Point = 1
                    },
                    new Score {
                        Skill = energetic, Point = 2
                    }
                },
                PositionX = 350,
                PositionY = 400
            }).Entity;

            var NodeAC = context.Nodes.Add(new Node
            {
                IsRoot   = false,
                IsLeaf   = true,
                Text     = "Choice AC",
                VideoUrl = "/",
                Course   = course,
                Scores   = new List <Score> {
                    new Score {
                        Skill = empathy, Point = 0
                    },
                    new Score {
                        Skill = reactivity, Point = 1
                    },
                    new Score {
                        Skill = aggressivity, Point = 0
                    },
                    new Score {
                        Skill = leadership, Point = 2
                    },
                    new Score {
                        Skill = energetic, Point = 8
                    }
                },
                PositionX = 500,
                PositionY = 400
            }).Entity;

            var relations = new NodeRelation[]
            {
                new NodeRelation {
                    Parent = rootNode, Child = NodeA
                },
                new NodeRelation {
                    Parent = rootNode, Child = NodeB
                },
                new NodeRelation {
                    Parent = rootNode, Child = NodeC
                },
                new NodeRelation {
                    Parent = NodeA, Child = NodeAA
                },
                new NodeRelation {
                    Parent = NodeA, Child = NodeAB
                },
                new NodeRelation {
                    Parent = NodeA, Child = NodeAC
                }
            };

            foreach (var rel in relations)
            {
                context.NodeRelations.Add(rel);
            }

            course.Nodes.Add(rootNode);
            course.Nodes.Add(NodeA);
            course.Nodes.Add(NodeB);
            course.Nodes.Add(NodeC);
            course.Nodes.Add(NodeAA);
            course.Nodes.Add(NodeAB);
            course.Nodes.Add(NodeAC);

            context.SaveChanges();
        }
        public IHttpActionResult CourseData(string coursename)
        {
            if (courses.ContainsKey(coursename))
            {
                return(Ok(courses[coursename]));
            }

            Course course = null;
            String json   = String.Empty;

            try
            {
                using (var webClient = new WebClient())
                {
                    json   = webClient.DownloadString(string.Format(Constants.COURSE_DATA_URL, coursename));
                    course = JsonConvert.DeserializeObject <Course>(json);
                    CourseSimpleModule.ResetIndex();

                    course.ID = coursename;

                    NameValueCollection postData = new NameValueCollection()
                    {
                        { "courseId", coursename }
                    };
                    byte[] responsebytes = webClient.UploadValues(Constants.COURSE_PAYLOAD_DATA_URL, postData);
                    json = Encoding.UTF8.GetString(responsebytes);
                    var coursePayload = JsonConvert.DeserializeObject <CoursePayload>(json);
                    if (coursePayload == null)
                    {
                        logger.Error("Couldn't retrieve course. Requested course={0}", coursename);
                        throw new Exception("Couldn't retrieve course data. Please check log file.");
                    }
                    course.SupportsWideScreenVideoFormats = coursePayload.SupportsWideScreenVideoFormats;

                    json           = webClient.DownloadString(string.Format(Constants.COURSE_CONTENT_DATA_URL, coursename));
                    course.Content = JsonConvert.DeserializeObject <CourseContent>(json);

                    SetupAuthenticationCookie(webClient);
                    // TODO: check if the user has access to exercise files.
                    try
                    {
                        json = webClient.DownloadString(string.Format(Constants.COURSE_EXERCISE_FILES_URL, coursename));
                        course.ExerciseFiles = JsonConvert.DeserializeObject <ExerciseFiles>(json);
                    }
                    catch
                    {
                    }

                    json = webClient.DownloadString(string.Format(Constants.COURSE_TRANSCRIPT_URL, coursename));
                    var transcript = JsonConvert.DeserializeObject <Transcript>(json);

                    course.Content.Modules.ForEachWithIndex((module, moduleIndex) =>
                    {
                        module.Clips.ForEachWithIndex((clip, clipIndex) =>
                        {
                            clip.ModuleIndex    = moduleIndex;
                            clip.VideoDirectory = GetVideoFolderStructure(course.Title, module.Title, clip);
                            clip.TranscriptClip = transcript.Modules[moduleIndex].Clips[clipIndex];
                        });
                    });
                }
            }
            catch (Exception exception)
            {
                return(HandleException(exception));
            }

            courses.Add(course.ID, course);
            return(Ok(course));
        }
        private async void SaveCourseInformation(CourseSimpleClip clip)
        {
            String courseName = clip.ID.Substring(0, clip.ID.IndexOf("|"));
            Course course     = null;

            courses.TryGetValue(courseName, out course);
            if (course == null)
            {
                return;
            }
            var descriptionFile = GetBaseFolderStructure(course.Title) + "\\description.txt";
            var levelFile       = GetBaseFolderStructure(course.Title) + "\\level.txt";
            var authorsFile     = GetBaseFolderStructure(course.Title) + "\\authors.txt";
            var dateFile        = GetBaseFolderStructure(course.Title) + "\\date.txt";
            var excerciceFile   = GetBaseFolderStructure(course.Title) + "\\" + course.Title.ToValidFileName() + "-excercice.zip";

            if (!File.Exists(descriptionFile))
            {
                File.WriteAllText(descriptionFile, course.Description);
            }
            if (!File.Exists(levelFile))
            {
                File.WriteAllText(levelFile, course.Level);
            }
            if (!File.Exists(dateFile))
            {
                File.WriteAllText(dateFile, DateTime.Parse(course.ReleaseDate).ToString("dd/MM/yyyy"));
            }
            if (!File.Exists(authorsFile))
            {
                String separator = "";
                String authors   = "";
                foreach (Author author in course.Authors)
                {
                    authors   = separator + author.FirstName + " " + author.LastName;
                    separator = ", ";
                }
                File.WriteAllText(authorsFile, String.Join(", ", authors));
            }
            if (!File.Exists(excerciceFile))
            {
                if (course.ExerciseFiles != null)
                {
                    try
                    {
                        using (var client = new WebClient())
                            using (var regStream = await client.OpenReadTaskAsync(course.ExerciseFiles.exerciseFilesUrl))
                                using (var stream = new ThrottledStream(regStream, 115200))
                                {
                                    byte[] buffer = new byte[1024];

                                    using (var fileStream = File.OpenWrite(excerciceFile))
                                    {
                                        for (;;)
                                        {
                                            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                                            if (bytesRead == 0)
                                            {
                                                await Task.Yield();

                                                break;
                                            }

                                            fileStream.Write(buffer, 0, bytesRead);
                                        }
                                    }
                                }
                    } catch
                    {
                    }
                }
            }
        }
Example #40
0
 public void SetCourse(Course course)
 {
     Course = course;
 }
        // GET: AbsencePerStudent
        public ActionResult AbsencePerStudent(int courseId)
        {
            Course course = context.GetCourseById(courseId);

            return(View(course));
        }
        // GET: Course
        public ActionResult Course(int courseId)
        {
            Course course = context.GetCourseById(courseId);

            return(View(course));
        }
Example #43
0
        public ActionResult Edit(int id)
        {
            Course course = unit.CourseManager.GetById(id);

            return(View(course));
        }
        public static void Initialize(SchoolContext context)
        {
            context.Database.EnsureCreated();

            if (context.Students.Any())
            {
                return;
            }

            var students = new Student[]
            {
                new Student {
                    FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01")
                },
                new Student {
                    FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2002-09-01")
                },
                new Student {
                    FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2003-09-01")
                },
                new Student {
                    FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01")
                },
                new Student {
                    FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2002-09-01")
                },
                new Student {
                    FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2001-09-01")
                },
                new Student {
                    FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2003-09-01")
                },
                new Student {
                    FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01")
                }
            };

            foreach (Student s in students)
            {
                context.Students.Add(s);
            }
            context.SaveChanges();

            var instructors = new Instructor[]
            {
                new Instructor {
                    FirstMidName = "Kim", LastName = "Abercrombie",
                    HireDate     = DateTime.Parse("1995-03-11")
                },
                new Instructor {
                    FirstMidName = "Fadi", LastName = "Fakhouri",
                    HireDate     = DateTime.Parse("2002-07-06")
                },
                new Instructor {
                    FirstMidName = "Roger", LastName = "Harui",
                    HireDate     = DateTime.Parse("1998-07-01")
                },
                new Instructor {
                    FirstMidName = "Candace", LastName = "Kapoor",
                    HireDate     = DateTime.Parse("2001-01-15")
                },
                new Instructor {
                    FirstMidName = "Roger", LastName = "Zheng",
                    HireDate     = DateTime.Parse("2004-02-12")
                }
            };

            foreach (Instructor i in instructors)
            {
                context.Instructors.Add(i);
            }
            context.SaveChanges();

            var departments = new Department[]
            {
                new Department {
                    Name         = "English", Budget = 350000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
                },
                new Department {
                    Name         = "Mathematics", Budget = 100000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID
                },
                new Department {
                    Name         = "Engineering", Budget = 350000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID
                },
                new Department {
                    Name         = "Economics", Budget = 100000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID
                }
            };

            foreach (Department d in departments)
            {
                context.Departments.Add(d);
            }
            context.SaveChanges();

            var courses = new Course[]
            {
                new Course {
                    CourseID     = 1050, Title = "Chemistry", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Engineering").DepartmentID
                },
                new Course {
                    CourseID     = 4022, Title = "Microeconomics", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Economics").DepartmentID
                },
                new Course {
                    CourseID     = 4041, Title = "Macroeconomics", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Economics").DepartmentID
                },
                new Course {
                    CourseID     = 1045, Title = "Calculus", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "Mathematics").DepartmentID
                },
                new Course {
                    CourseID     = 3141, Title = "Trigonometry", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "Mathematics").DepartmentID
                },
                new Course {
                    CourseID     = 2021, Title = "Composition", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "English").DepartmentID
                },
                new Course {
                    CourseID     = 2042, Title = "Literature", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "English").DepartmentID
                },
            };

            foreach (Course c in courses)
            {
                context.Courses.Add(c);
            }
            context.SaveChanges();

            var officeAssignments = new OfficeAssignment[]
            {
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID,
                    Location     = "Smith 17"
                },
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID,
                    Location     = "Gowan 27"
                },
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID,
                    Location     = "Thompson 304"
                },
            };

            foreach (OfficeAssignment o in officeAssignments)
            {
                context.OfficeAssignments.Add(o);
            }
            context.SaveChanges();

            var courseInstructors = new CourseAssignment[]
            {
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Chemistry").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Chemistry").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Zheng").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Macroeconomics").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Zheng").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Calculus").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Trigonometry").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Composition").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
                },
                new CourseAssignment {
                    CourseID     = courses.Single(c => c.Title == "Literature").CourseID,
                    InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
                },
            };

            foreach (CourseAssignment ci in courseInstructors)
            {
                context.CourseAssignments.Add(ci);
            }
            context.SaveChanges();

            var enrollments = new Enrollment[]
            {
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.A
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.C
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Macroeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Calculus").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Trigonometry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Li").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Justice").ID,
                    CourseID  = courses.Single(c => c.Title == "Literature").CourseID,
                    Grade     = Grade.B
                }
            };

            foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                    s.Student.ID == e.StudentID &&
                    s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
Example #45
0
 public SelectedFileDto(Course course, File file)
 {
     Course = course;
     File   = file;
 }
Example #46
0
        public async Task <IActionResult> CreateCourse([FromBody] Course course)
        {
            var newCourse = await course.Save();

            return(Ok(newCourse));
        }
Example #47
0
        public ActionResult Details(Guid id)
        {
            Course course = _coursesRepository.GetCourse(id);

            return(View(course));
        }
        public static void Initialize(SchoolContext context)
        {
            context.Database.EnsureCreated();

            // Look for any students.
            if (context.Students.Any())
            {
                return;   // DB has been seeded
            }

            var students = new Student[]
            {
                new Student {
                    FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2019-09-01")
                },
                new Student {
                    FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2017-09-01")
                },
                new Student {
                    FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2018-09-01")
                },
                new Student {
                    FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2017-09-01")
                },
                new Student {
                    FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2017-09-01")
                },
                new Student {
                    FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2016-09-01")
                },
                new Student {
                    FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2018-09-01")
                },
                new Student {
                    FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2019-09-01")
                }
            };

            foreach (Student s in students)
            {
                context.Students.Add(s);
            }
            context.SaveChanges();

            var courses = new Course[]
            {
                new Course {
                    ID = 1050, Title = "Chemistry", Credits = 3
                },
                new Course {
                    ID = 4022, Title = "Microeconomics", Credits = 3
                },
                new Course {
                    ID = 4041, Title = "Macroeconomics", Credits = 3
                },
                new Course {
                    ID = 1045, Title = "Calculus", Credits = 4
                },
                new Course {
                    ID = 3141, Title = "Trigonometry", Credits = 4
                },
                new Course {
                    ID = 2021, Title = "Composition", Credits = 3
                },
                new Course {
                    ID = 2042, Title = "Literature", Credits = 4
                }
            };

            foreach (Course c in courses)
            {
                context.Courses.Add(c);
            }
            context.SaveChanges();

            var enrollments = new Enrollment[]
            {
                new Enrollment {
                    StudentID = 1, CourseID = 1050, Grade = Grade.A
                },
                new Enrollment {
                    StudentID = 1, CourseID = 4022, Grade = Grade.C
                },
                new Enrollment {
                    StudentID = 1, CourseID = 4041, Grade = Grade.B
                },
                new Enrollment {
                    StudentID = 2, CourseID = 1045, Grade = Grade.B
                },
                new Enrollment {
                    StudentID = 2, CourseID = 3141, Grade = Grade.F
                },
                new Enrollment {
                    StudentID = 2, CourseID = 2021, Grade = Grade.F
                },
                new Enrollment {
                    StudentID = 3, CourseID = 1050
                },
                new Enrollment {
                    StudentID = 4, CourseID = 1050
                },
                new Enrollment {
                    StudentID = 4, CourseID = 4022, Grade = Grade.F
                },
                new Enrollment {
                    StudentID = 5, CourseID = 4041, Grade = Grade.C
                },
                new Enrollment {
                    StudentID = 6, CourseID = 1045
                },
                new Enrollment {
                    StudentID = 7, CourseID = 3141, Grade = Grade.A
                },
            };

            foreach (Enrollment e in enrollments)
            {
                context.Enrollments.Add(e);
            }
            context.SaveChanges();
        }
Example #49
0
 public CourseResult(Course course, string update, string owner)
 {
     _Course = course;
     _Update = update;
     _Owner  = owner;
 }
Example #50
0
 public void CreateCourseNullOrEmptyTest()
 {
     string name   = string.Empty;
     Course actual = school.CreateCourse(name);
 }
Example #51
0
        private static bool RecursiveCourseAcheivableCheckHelper(MainCurriculum curriculum, List <SatelliteInformation> satList, Course c, CourseCategory courseCategory)
        {
            if (courseCategory == curriculum.Root)
            {
                return(true);
            }
            else
            {
                List <CourseCategory> allowedCourseCategories = new List <CourseCategory>();

                for (int i = 0; i < courseCategory.InputGates.Count; i++)
                {
                    var graphEdge = courseCategory.InputGates[i];

                    if (!graphEdge.IsAllowedAllCredits(curriculum.StudentCredit))
                    {
                        continue;
                    }

                    bool graphEdgeCon = true;

                    for (int j = 0; j < graphEdge.CertificateList.Count; j++)
                    {
                        var crt = graphEdge.CertificateList[j];

                        for (int m = 0; m < crt.ConstraintList.Count; m++)
                        {
                            var constraint = crt.ConstraintList[m];

                            if (constraint is MinNumberMaxNumberOfCoursesConstraint)
                            {
                                graphEdgeCon = constraint.IsOk(satList[courseCategory.Id].NumberOfCoursesPassed + 1);
                            }
                            else if (constraint is MinUnitsMaxUnitsOfCoursesConstraint)
                            {
                                graphEdgeCon = constraint.IsOk(satList[courseCategory.Id].UnitsOfCoursesPassed + c.Units);
                            }
                            else if (constraint is NumberOfCoursesMustBeLabOrWorkshopConstraint)
                            {
                                graphEdgeCon = constraint.IsOk(satList[courseCategory.Id].NumberOfWorkshopOrLabPassed + (c.IsLabOrWorkshop() ? 1 : 0));
                            }
                            else if (constraint is UnitOfCoursesMustBeLabOrWorkshopConstraint)
                            {
                                graphEdgeCon = constraint.IsOk(satList[courseCategory.Id].UnitsOfWorkshopOrLabPassed + (c.IsLabOrWorkshop() ? c.Units : 0));
                            }
                            else
                            {
                                throw new ArgumentException();
                            }

                            if (!graphEdgeCon)
                            {
                                break;
                            }
                        }
                        if (!graphEdgeCon)
                        {
                            break;
                        }
                    }

                    if (graphEdgeCon)
                    {
                        allowedCourseCategories.Add(graphEdge.SrcCourseCategory);
                    }
                }

                bool suuc = false;
                for (int i = 0; i < allowedCourseCategories.Count; i++)
                {
                    var accc = allowedCourseCategories[i];
                    if (RecursiveCourseAcheivableCheckHelper(curriculum, satList, c, accc))
                    {
                        suuc = true;
                        break;
                    }
                }
                return(suuc);
            }
        }
Example #52
0
        private FlashcardsStatistics ToFlashcardsStatistics(List <UserFlashcardsVisit> userFlashcardsVisits, Course course)
        {
            var result = new FlashcardsStatistics();

            var visitsGroupedByFlashcard = userFlashcardsVisits.GroupBy(x => x.FlashcardId).ToDictionary(x => x.Key);

            foreach (var unit in course.GetUnitsNotSafe())
            {
                var flashcards = unit.Flashcards;
                foreach (var flashcard in flashcards)
                {
                    var flashcardStat = new FlashcardStatistic {
                        FlashcardId = flashcard.Id, UnitId = unit.Id, UnitTitle = unit.Title
                    };

                    if (visitsGroupedByFlashcard.TryGetValue(flashcard.Id, out var group))
                    {
                        var uniqueUsers = new HashSet <string>();
                        foreach (var e in group)
                        {
                            uniqueUsers.Add(e.UserId);
                            flashcardStat.Statistics.Add(e.Rate);
                        }

                        flashcardStat.UniqueVisitCount = uniqueUsers.Count;
                        flashcardStat.VisitCount       = group.Count();
                    }

                    result.Statistics.Add(flashcardStat);
                }
            }

            return(result);
        }
 public override string ToString()
 {
     return($"[{Id},{Resource},{Course.ToString()},{Notes}]");
 }
Example #54
0
 private void Model_Fetch(Course course, InstructorEdit instructor)
 {
     this.InjectFrom(course);
     Instructor = instructor;
 }
Example #55
0
        public async Task <Course> CreateCourse(CreateCourseDto input)
        {
            if (input.EducatorId == null)
            {
                long[] a = new long[0];
                input.EducatorId = a;
            }
            if (input.TenantId == null)
            {
                long[] b = new long[0];
                input.TenantId = b;
            }
            if (input.EducatorId.Length > 0)
            {
                var isHaveRightEducator = await _checkEdition.HaveCreateCourseRight <Educator>(input.EducatorId);

                if (!isHaveRightEducator)
                {
                    throw new Exception("No right to create course for educator !");
                }
            }

            if (input.TenantId.Length > 0)
            {
                var isHaveRight = await _checkEdition.HaveCreateCourseRight <Tenant>(input.TenantId);

                if (!isHaveRight)
                {
                    throw new Exception("No right to create course tenant !");
                }
            }

            var imagePath = await _blobService.InsertFile(input.File);

            var course = new Course
            {
                Title       = input.Title,
                Description = input.Description,
                Quota       = input.Quota,
                Address     = input.Address,
                OnlineVideo = input.OnlineVideo,
                Certificate = input.Certificate,
                CertificateOfParticipation = input.CertificateOfParticipation,
                DurationCount    = input.DurationCount,
                DurationType     = input.DurationType,
                Requirements     = input.Requirements,
                Teachings        = input.Teachings,
                Price            = input.Price,
                IsActive         = true,
                DiscountPrice    = input.DiscountPrice,
                StartDate        = input.StartDate,
                EndDate          = input.EndDate,
                CategoryId       = input.CategoryId,
                LocationId       = input.LocationId,
                OwnerType        = input.OwnerType,
                OwnerId          = input.OwnerId,
                ShortDescription = input.ShortDescription,
                ImagePath        = imagePath
            };

            await _courseRepository.AddAsync(course);

            var count = (input.TenantId.Length > input.EducatorId.Length)
                ? input.TenantId.Length
                : input.EducatorId.Length;

            for (var i = 0; i < count; i++)
            {
                var givenCourse = new GivenCourse
                {
                    CourseId = course.Id,
                };
                if (input.TenantId.Length > i)
                {
                    givenCourse.TenantId = input.TenantId[i];
                }

                if (input.EducatorId.Length > i)
                {
                    givenCourse.EducatorId = input.EducatorId[i];
                }
                await _givenCourseRepository.AddAsync(givenCourse);
            }
            return(course);
        }
Example #56
0
 public void Create(Course course)
 {
     course.Id = Database.Courses.Max(x => x.Id) + 1;
     Database.Courses.Add(course);
 }
Example #57
0
        private static bool Acheivable(bool[] visited, bool[] achivable, MainCurriculum curriculum, List <SatelliteInformation> satList, Course c, int cntPassedUnits, int currentTermNumber)
        {
            //memoization :=> dynamic programming
            if (visited[c.Id])
            {
                return(achivable[c.Id]);
            }


            if (!c.IsAvailable())
            {
                return(false);
            }
            else if (c.IsPassed)
            {
                return(false);
            }
            else if (c.MinRequireTerm > currentTermNumber)
            {
                return(false);
            }
            else if (c.MinReuireUnits > cntPassedUnits)
            {
                return(false);
            }

            for (int i = 0; i < c.PrerequisiteCourses.Count; i++)
            {
                var pr = c.PrerequisiteCourses[i];
                if (!pr.IsPassed)
                {
                    if (pr.NumberOfFailed > 1)
                    {
                        if (!Acheivable(visited, achivable, curriculum, satList, pr, cntPassedUnits, currentTermNumber))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            for (int i = 0; i < c.RequisiteCourses.Count; i++)
            {
                var r = c.RequisiteCourses[i];

                if (!r.IsAvailable())
                {
                    return(false);
                }
                if (r.IsPassed == false && !Acheivable(visited, achivable, curriculum, satList, r, cntPassedUnits, currentTermNumber))
                {
                    return(false);
                }
            }



            var res = RecursiveCourseAcheivableCheck(curriculum, satList, c);

            //memoization
            visited[c.Id]   = true;
            achivable[c.Id] = res;

            return(res);
        }
Example #58
0
        private static bool RecursiveCourseAcheivableCheck(MainCurriculum curriculum, List <SatelliteInformation> satList, Course c)
        {
            var  ccLst = c.CourseCategories;
            bool succ  = false;

            for (int i = 0; i < ccLst.Count; i++)
            {
                var cc = ccLst[i];
                if (RecursiveCourseAcheivableCheckHelper(curriculum, satList, c, cc))
                {
                    succ = true;
                    break;
                }
            }

            return(succ);
        }
Example #59
0
 public CourseTypeList(Course course)
 {
     this.currentType = course.CourseType;
 }
Example #60
0
 public StudentWithdrawn(Student student, Course course)
 {
     Student = student ?? throw new ArgumentNullException(nameof(student));
     Course  = course ?? throw new ArgumentNullException(nameof(course));
 }