コード例 #1
0
        public void created_course_is_assigned_to_correct_instructor()
        {
            //using (var Uow = new MOOCollab2UOW())
            using (var Uow = new TestDb())
            {
                //Arrange
                var courseRepo = new CourseRepository(Uow);
                var instructorRepo = new InstructorRepository(Uow);
                var testInstructor = instructorRepo.Find(1);

                courseRepo.Create(new Course
                {
                    OwnerId = 1,//course to instructor with Id of one
                    Title = "Test",
                    Resume = "Argh",//test text
                    Status = true
                });
                courseRepo.SaveChanges();
            }

            //using (var Uow = new MOOCollab2UOW())
            using (var Uow = new TestDb())
            {
                //Arrange
                var instructorRepo = new InstructorRepository(Uow);

                //Act
                var instructor = instructorRepo.FindAll()
                                .Include(i => i.Courses)
                                .FirstOrDefault(i => i.Id == 1);
                //assert  //Check if instructor has the new course
                Assert.IsNotNull(instructor.Courses.FirstOrDefault(c => c.Resume == "Argh"));
            }
        }
コード例 #2
0
        public JsonResult AssignTo(int CourseID, int TeacherID)
        {
            CourseRepository courseRepository = new CourseRepository();
            CourseSubjectRepository courseSubjectRepo = new CourseSubjectRepository();
            TeacherRepository teacherRepository = new TeacherRepository();
            Teacher teacher = new Teacher();
            teacher = teacherRepository.GetById(TeacherID);
            List<SelectListItem> listSubjects = new List<SelectListItem>();
            var allSubjects = courseSubjectRepo.GetAll(filter: s => s.CourseID == CourseID);

            foreach (var item in allSubjects)
            {
                if (teacher.CourseSubject.Any(cs => cs.CourseID == CourseID && cs.SubjectID == item.SubjectID))
                {
                    listSubjects.Add(new SelectListItem() { Text = item.Subject.Name, Value = item.SubjectID.ToString(), Selected = true });
                }
                else
                {
                    listSubjects.Add(new SelectListItem() { Text = item.Subject.Name, Value = item.SubjectID.ToString(), Selected = false });
                }

            }

            return Json(listSubjects, JsonRequestBehavior.AllowGet);
        }
コード例 #3
0
        public ActionResult AssignToCourse(int id)
        {
            TeacherRepository teacherRepo = new TeacherRepository();
            Teacher teacher = teacherRepo.GetById(id);
            AdminControllerTeacherVM teacherModel = new AdminControllerTeacherVM();
            CourseRepository courseRepo = new CourseRepository();
            List<Course> courses = new List<Course>();

            teacherModel.FirstName = teacher.FirstName;
            teacherModel.LastName = teacher.LastName;
            teacherModel.Id = id;
            courses = courseRepo.GetAll().OrderBy(c => c.Name).ToList();

            List<SelectListItem> SelectList = new List<SelectListItem>();
            SelectListItem select = null;
            teacherModel.CourseSubjectList = teacher.CourseSubject.ToList();

            foreach (var item in courses)
            {
                select = new SelectListItem() { Text = item.Name, Value = item.Id.ToString() };
                SelectList.Add(select);
            }
            teacherModel.ListItems = SelectList;

            return View(teacherModel);
        }
コード例 #4
0
 public ActionResult Index()
 {
     if (AuthenticationManager.LoggedUser == null)
     {
         return RedirectToAction("Login", "Default");
     }
     Student student = new Student();
     StudentRepository studentRepository = new StudentRepository();
     student = studentRepository.GetById(AuthenticationManager.LoggedUser.Id);
     StudentControllerStudentVM model = new StudentControllerStudentVM();
     Course course = new Course();
     CourseRepository courseRepository = new CourseRepository();
     course = courseRepository.GetAll(filter: c => c.Id == student.CourseID).FirstOrDefault();
     List<Subject> subjectList = new List<Subject>();
     CourseSubjectRepository courseSubjectRepository = new CourseSubjectRepository();
     subjectList = courseSubjectRepository.GetAll(filter: c => c.CourseID == course.Id).Select(s => s.Subject).ToList();
     List<string> subjectNames = new List<string>();
     foreach (var subject in subjectList)
     {
         subjectNames.Add(subject.Name);
     }
     model.Subjects = subjectNames;
     model.FirstName = student.FirstName;
     model.LastName = student.LastName;
     model.StudentID = AuthenticationManager.LoggedUser.Id;
     model.Course = course.Name;
     model.FaculityNumber = student.FacultyNumber;
     return View(model);
 }
コード例 #5
0
        public ActionResult AddSubject(int? id)
        {
            TeacherAddSubjectVM model = new TeacherAddSubjectVM();
            CourseRepository cRepo = new CourseRepository();
            UserRepository<Teacher> teacherRepo = new UserRepository<Teacher>();

            List<SelectListItem> list = new List<SelectListItem>();

            Teacher teacher = teacherRepo.GetByID(id.Value);

            model.Title = teacher.Title.Name;
            model.FirstName = teacher.FirstName;
            model.LastName = teacher.LastName;
            model.TeacherID = teacher.ID;

            var courses = cRepo.GetAll();

            foreach (var item in courses)
            {
                list.Add(new SelectListItem() { Text = item.Name, Value = item.ID.ToString() });
            }
            model.CoursesList = list;

            return View(model);
        }
コード例 #6
0
        public void UpdateTest()
        {
            DbContextHelper.Init(typeof(CourseDbContext), GlobalSettings.DATABASE.ConnectionString, 8);

            CourseRepository repo = new CourseRepository();

            Assert.AreEqual(true, repo.Update(3, "Comupter Network", "Compter Network Foundation", 2));
        }
コード例 #7
0
        public void AllTest()
        {
            DbContextHelper.Init(typeof(CourseDbContext), GlobalSettings.DATABASE.ConnectionString, 8);

            CourseRepository repo = new CourseRepository();
            var result = repo.All();

            Assert.AreEqual(2, result.Count());
        }
コード例 #8
0
        public UnitOfWork(SchoolContext ctx)
        {
            this.context = ctx;
            CoursesFromGenericRepo = new CourseRepository(context);
            CourseRepo = new CourseRepository(context);
            StudentGenericRepo = new StudentRepository(context);
            StudentRepo = new StudentRepository(context);

        }
コード例 #9
0
        public void Course_And_Instructor_By_Id_data_verified()
        {
            Course testcourse;
            //using (var Uow = new MOOCollab2UOW())
            using (var Uow = new TestDb())
            {
                //Arrange
                var courseRepo = new CourseRepository(Uow);
                testcourse = courseRepo.CourseAndInstructorByCourseId(1);

            }
            Assert.IsNotNull(testcourse.OwnerId);
        }
コード例 #10
0
        public void delete_applies_soft_delete()
        {
            //var repo = new CourseRepository(new MOOCollab2UOW());
            var repo = new CourseRepository(new TestDb());

            var testCourse = new Course { Id = 1, Status = true };

            //act
            repo.Delete(testCourse);

            var changedCourse = repo.CourseAndInstructorByCourseId(1);//get changed course
            //assert
            Assert.IsFalse(changedCourse.Status);
            Assert.IsNull(changedCourse.Groups.FirstOrDefault(g => g.Status == true));
        }
コード例 #11
0
        public void CanCreate()
        {
            _testDatabase.RunAndRollback(dbContext =>
            {
                var course = new Course
                {
                    Name = "Snijden"
                };

                var createdCourse = new CourseRepository(dbContext).Create(course);

                Assert.NotNull(createdCourse);
                Assert.True(createdCourse.Id > 0);
                Assert.Equal(course.Name, createdCourse.Name);
            });
        }
コード例 #12
0
        public async void AddCourses_AddsCoursesWithSameIdFromTheListOfSudentCourses()
        {
            //Arrange
            var connectionBuilder = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionBuilder.ToString());
            var options    = new DbContextOptionsBuilder <ApplicationDbContext>()
                             .UseSqlite(connection)
                             .Options;

            using var context = new ApplicationDbContext(options);
            context.Database.OpenConnection();
            context.Database.EnsureCreated();
            var studentRepository = new StudentRepository(context);
            var courseRepository  = new CourseRepository(context);

            var student = StudentHelpers.GetStudent();
            var courses = CourseHelpers.GetCourses();

            //Act
            foreach (var course in courses)
            {
                await courseRepository.Insert(course);
            }
            await studentRepository.Insert(student);

            await studentRepository.AddManyCourses(new List <int> {
                1, 2, 3
            }, "5");

            var numberOfCoursesAfterInsertion = (await studentRepository.GetCourses("5")).Count();

            //Assert
            Assert.Equal(3, numberOfCoursesAfterInsertion);
            await Assert.ThrowsAsync <AppUserException>(
                () => studentRepository.AddManyCourses(new List <int> {
                1, 2, 3
            }, "5"));

            await Assert.ThrowsAsync <AppUserException>(
                () => studentRepository.AddManyCourses(new List <int> {
                10, 29, 13
            }, "5"));
        }
コード例 #13
0
ファイル: UnitOfWork.cs プロジェクト: Rashid75/Fyp
 public UnitOfWork(FypDbContext db)
 {
     _context = db;
     Campus = new CampusRepository(_context);
     Department = new DepartmentRepository(_context);
     Batch = new BatchRepository(_context);
     Section = new SectionRepository(_context);
     Student = new StudentRepository(_context);
     File = new FileRepository(_context);
     Teacher = new TeacherRepository(_context);
     EnrollDep = new EnrollDepartmentRepository(_context);
     EnrollBatch = new EnrollBatchRepository(_context);
     EnrollSection = new EnrollSectionRepository(_context);
     Course = new CourseRepository(_context);
     CourseToDep = new CourseToDepRepository(_context);
     StudentRegistration = new StudentRegistrationRepository(_context);
     subjectallocate = new SubjectAllocatRepository(_context);
 }
コード例 #14
0
        public ActionResult EditStudent(StudentVM viewModel)
        {
            if (ModelState.IsValid)
            {
                viewModel.Student.Major         = MajorRepository.Get(viewModel.Student.Major.MajorId);
                viewModel.Student.Address.State = StateRepository.Get(viewModel.Student.Address.State.StateAbbreviation);

                StudentRepository.Edit(viewModel.Student);
                return(RedirectToAction("List"));
            }
            else
            {
                viewModel.SetStateItems(StateRepository.GetAll());
                viewModel.SetCourseItems(CourseRepository.GetAll());
                viewModel.SetMajorItems(MajorRepository.GetAll());
                return(View(viewModel));
            }
        }
コード例 #15
0
        public ActionResult DeleteImage(string imageName)
        {
            var uploader = new ImageUploader();

            var courseRepository = new CourseRepository(_context);
            var course           = courseRepository.GetByImageName(imageName);

            if (course != null)
            {
                course.Image = null;
                courseRepository.Update(course);
                _context.Save(_loggedUser);
            }

            uploader.DeleteFile(imageName);

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #16
0
 public ManageController(ApplicationDbContext context,
                         UserManager <ApplicationUser> userManager,
                         SignInManager <ApplicationUser> signInManager,
                         IEmailSender emailSender,
                         ILogger <ManageController> logger,
                         UrlEncoder urlEncoder,
                         IHostingEnvironment appEnvironment)
 {
     _context          = context;
     _userManager      = userManager;
     _signInManager    = signInManager;
     _emailSender      = emailSender;
     _logger           = logger;
     _urlEncoder       = urlEncoder;
     _appEnvironment   = appEnvironment;
     _userRepository   = new UserRepository(_context);
     _courseRepository = new CourseRepository(_context);
 }
コード例 #17
0
        public ActionResult EditCourse(Course course)
        {
            if (string.IsNullOrEmpty(course.CourseName))
            {
                ModelState.AddModelError("CourseName", "Please Enter a Course Name");
            }

            if (ModelState.IsValid)
            {
                CourseRepository.Edit(course);
                return(RedirectToAction("Courses"));
            }

            else
            {
                return(View(course));
            }
        }
コード例 #18
0
        public async Task Add_Student_To_Invalid_Course_Test()
        {
            CourseRepository repository = new CourseRepository(context, logger);

            var student = new Student
            {
                Name        = "Sara Bailey Winston",
                Email       = "*****@*****.**",
                DateOfBirth = new System.DateTime(2000, 03, 12)
            };

            var course = new Course {
                Id = Guid.NewGuid(), Name = "Invalid subject", Capacity = 0
            };
            var result = await repository.AddStudentToCourseAsync(course, student);

            Assert.False(result);
        }
コード例 #19
0
        public ActionResult Edit(StudentVM studentVM)
        {
            studentVM.Student.Courses = new List <Course>();

            foreach (var id in studentVM.SelectedCourseIds)
            {
                studentVM.Student.Courses.Add(CourseRepository.Get(id));
            }

            studentVM.Student.Major = MajorRepository.Get(studentVM.Student.Major.MajorId);

            studentVM.Student.Address.State = StateRepository.Get(studentVM.Student.Address.State.StateAbbreviation);

            StudentRepository.Edit(studentVM.Student);
            StudentRepository.SaveAddress(studentVM.Student.StudentId, studentVM.Student.Address);

            return(RedirectToAction("List"));
        }
コード例 #20
0
        public void CourseRepositoryTests_AddedCoursesShouldBeAppearInRepository()
        {
            // Arrange

            //SUT: System Under Test
            var sut    = new CourseRepository();
            var course = new Course {
                Id = 1, Name = "Test Course"
            };

            // Act
            sut.Add(course);
            var result = sut.GetById(course.Id);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(course, result);
        }
コード例 #21
0
        public ActionResult EditCourse(Course model)
        {
            if (string.IsNullOrEmpty(model.CourseName))
            {
                ModelState.AddModelError("CourseName", "Please enter the course name.");
            }

            if (ModelState.IsValid)
            {
                CourseRepository.Edit(model);
                return(RedirectToAction("Courses"));
            }

            else
            {
                return(View(model));
            }
        }
コード例 #22
0
 public UnitOfWork(MemoContext context)
 {
     this.dbContext = new MemoContext();
     Answers        = new AnswerRepository(dbContext);
     Cards          = new CardRepository(dbContext);
     CardTypes      = new CardTypeRepository(dbContext);
     Categories     = new CategoryRepository(dbContext);
     Comments       = new CommentRepository(dbContext);
     Course         = new CourseRepository(dbContext);
     DeckCourses    = new DeckCourseRepository(dbContext);
     Decks          = new DeckRepository(dbContext);
     Reports        = new ReportRepository(dbContext);
     Roles          = new RoleRepository(dbContext);
     Statistics     = new StatisticRepository(dbContext);
     UserCourses    = new UserCourseRepository(dbContext);
     Users          = new UserRepository(dbContext);
     UserRoles      = new UserRoleRepository(dbContext);
 }
コード例 #23
0
        public ActionResult EditStudent(int id)
        {
            var viewModel = new StudentVM();

            viewModel.Student = StudentRepository.Get(id);
            viewModel.SetCourseItems(CourseRepository.GetAll());
            viewModel.SetMajorItems(MajorRepository.GetAll());

            if (viewModel.Student.Courses != null)
            {
                foreach (var course in viewModel.Student.Courses)
                {
                    viewModel.SelectedCourseIds.Add(course.CourseId);
                }
            }

            return(View(viewModel));
        }
コード例 #24
0
        public async void GetByIdTest()
        {
            var options = getOptions(nameof(GetByIdTest));

            await setup(options);

            using (var context = new CSAMSDbContext(options)) {
                // Initialize repository
                var repo = new CourseRepository(context);
                // Add actions
                var basicProgramming = await repo.GetByCode("CS101");

                var anotherBasicProgramming = await repo.GetById(basicProgramming.Id);

                // Add assertions
                Assert.Equal(basicProgramming, anotherBasicProgramming);
            }
        }
コード例 #25
0
        public async Task Contains_Test()
        {
            var options = new DbContextOptionsBuilder <ApplicationContext>()
                          .UseInMemoryDatabase(databaseName: "FindTestDatabase")
                          .Options;

            using (var context = new ApplicationContext(options))
            {
                context.Database.EnsureCreated();
                var repository = new CourseRepository(context);
                var newCourse  = new Course {
                    Name = "Test", LecturerId = 1
                };
                var contains = await repository.Contains(newCourse);

                Assert.That(contains, Is.EqualTo(false));
            }
        }
コード例 #26
0
        public FacultyHome(string userId)
        {
            InitializeComponent();

            uId = userId;

            AccountRepository ar = new AccountRepository();
            Account           ac = ar.GetAccount(userId);

            this.labelName.Text = "Welcome " + ac.Name;

            dataGridView1.Visible = false;

            SemesterRepository sr    = new SemesterRepository();
            List <Semester>    sList = new List <Semester>();

            sList = sr.GetAllSemesters();

            for (int i = 0; i < sList.Count(); i++)
            {
                comboBoxSemester.Items.Add(sList[i].Name);
            }
            this.comboBoxSemester.Text = "Spring 17-18";
            this.Controls.Add(this.comboBoxSemester);

            CourseAssignRepository car   = new CourseAssignRepository();
            List <CourseAssign>    cList = new List <CourseAssign>();

            cList = car.GetAllSections(userId, this.comboBoxSemester.Text);

            DataTable table = new DataTable();

            table.Columns.Add(" Course Name ", typeof(string));
            table.Columns.Add(" Section ", typeof(string));
            table.Columns.Add("Schedule ", typeof(string));

            for (int i = 0; i < cList.Count; i++)
            {
                CourseRepository cr = new CourseRepository();
                table.Rows.Add(cList[i].AssignedCourse, cList[i].Section, cr.GetOnlySchedule(comboBoxSemester.Text, cList[i].AssignedCourse, cList[i].Section));
            }
            dataGridView1.DataSource = table;
            dataGridView1.ReadOnly   = true;
        }
コード例 #27
0
        public async Task <ActionResult> Create(ClassViewModel viewModel)
        {
            var courseRepository = new CourseRepository(_context);
            var userRepository   = new UserRepository(_context);

            if (ModelState.IsValid)
            {
                try
                {
                    var course          = courseRepository.GetById(viewModel.CourseId);
                    var teacher         = (Teacher)userRepository.GetById(viewModel.TeacherId);
                    var classRepository = new ClassRepository(_context);
                    classRepository.Create(ClassViewModel.ToEntity(viewModel, course, teacher));

                    var affectedClassrooms = ResumeConcludedDeliveryPlans(course);
                    await SyncAccessesAsync(affectedClassrooms);

                    _context.Save(_loggedUser);
                    TempData["MessageType"]  = "success";
                    TempData["MessageTitle"] = Resource.ContentManagementToastrTitle;
                    TempData["Message"]      = Resource.ClassCreatedToastrMessage;
                    return(Redirect(TempData["BackURL"].ToString()));
                }
                catch (Exception ex)
                {
                    TempData["MessageType"]  = "error";
                    TempData["MessageTitle"] = Resource.ContentManagementToastrTitle;
                    TempData["Message"]      = ex.Message;
                }
            }

            const ContentType classType = ContentType.Vimeo;

            ViewBag.ContentTypes = new SelectList(classType.ToDataSource <ContentType>(), "Key", "Value");

            var activeCourses = courseRepository.ListActiveCourses();

            ViewBag.Courses = new SelectList(activeCourses, "Id", "Name");
            var activeTeachers = userRepository.ListActiveTeachers();

            ViewBag.Teachers = new SelectList(activeTeachers, "Id", "Name");

            return(View(viewModel));
        }
コード例 #28
0
        static void Main(string[] args)
        {
            var courseDatabase = new CourseDatabase();

            _teacherRepository = new TeacherRepository(courseDatabase);
            _courseRepository  = new CourseRepository(courseDatabase);

            var menuOption = MainMenu();

            while (menuOption < 5)
            {
                switch (menuOption)
                {
                case 1:
                    GetAllTeachers();
                    break;

                case 2:
                    GetAllCourses();
                    break;

                case 3:
                    AddTeacher();
                    break;

                case 4:
                    AddCourse();
                    break;

                case 5:
                    break;

                default:
                    Console.WriteLine("You chose an invalid option.");
                    Clear();
                    break;
                }

                if (menuOption != 5)
                {
                    menuOption = MainMenu();
                }
            }
        }
        public MemoryStream GenerateCSV()
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer    = new StreamWriter(outStream);

            // Headings
            writer.Write("SchoolCode" + delimiter);
            writer.Write("CourseCode" + delimiter);
            writer.Write("CourseName" + delimiter);
            writer.Write("CreditValue" + delimiter);
            writer.Write("GradeLower" + delimiter);
            writer.Write("GradeUpper");
            writer.Write(Environment.NewLine);

            // HIGH SCHOOL CLASSES ONLY
            // - Or more specifically, courses that offer more than zero credits

            // Get all classes
            // Make a list of all courses offered

            SchoolClassRepository classRepository  = new SchoolClassRepository(_dbConnectionString);
            CourseRepository      courseRepository = new CourseRepository(_dbConnectionString);
            SchoolRepository      schoolRepo       = new SchoolRepository(_dbConnectionString);

            List <Course> coursesWithCredits = courseRepository.GetAll().Where(x => x.Credits > 0 && x.CurrentlyOffered).ToList();

            foreach (School school in schoolRepo.GetAll().Where(x => x.IsHighSchool))
            {
                foreach (Course course in coursesWithCredits)
                {
                    writer.Write(stringContainer + school.GovernmentID + stringContainer + delimiter);
                    writer.Write(stringContainer + course.CourseCode + stringContainer + delimiter);
                    writer.Write(stringContainer + course.Name + stringContainer + delimiter);
                    writer.Write(stringContainer + course.Credits + stringContainer + delimiter);
                    writer.Write(stringContainer + course.LowGrade + stringContainer + delimiter);
                    writer.Write(stringContainer + course.HighGrade + stringContainer);
                    writer.Write(Environment.NewLine);
                }
            }

            writer.Flush();
            outStream.Flush();
            return(outStream);
        }
        public async void RemoveCourse_RemovesAcourseWithSameIdFromTheListOfSudentCourses()
        {
            //Arrange
            var connectionBuilder = new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            };
            var connection = new SqliteConnection(connectionBuilder.ToString());
            var options    = new DbContextOptionsBuilder <ApplicationDbContext>()
                             .UseSqlite(connection)
                             .Options;

            using var context = new ApplicationDbContext(options);
            context.Database.OpenConnection();
            context.Database.EnsureCreated();
            var TeacherRepository = new TeacherRepository(context);
            var courseRepository  = new CourseRepository(context);

            var teacher = TeacherHelpers.GetTeacher();
            var courses = CourseHelpers.GetCourses();

            //Act
            foreach (var course in courses)
            {
                await courseRepository.Insert(course);
            }
            await TeacherRepository.Insert(teacher);

            await TeacherRepository.AddCourse(1, "5");

            await TeacherRepository.AddCourse(2, "5");

            var numberOfCoursesAfterInsertion = (await TeacherRepository.GetCourses("5")).Count();
            await TeacherRepository.RemoveCourse(1, "5");

            var numberOfCoursesAfterRemoval = (await TeacherRepository.GetCourses("5")).Count();

            //Assert
            Assert.Equal(2, numberOfCoursesAfterInsertion);
            Assert.Equal(1, numberOfCoursesAfterRemoval);
            await TeacherRepository.RemoveCourse(2, "5");

            await Assert.ThrowsAsync <AppUserException>(
                () => TeacherRepository.GetCourses("5"));
        }
コード例 #31
0
        protected void bindCourseList()
        {
            ListToTable       lsttodt          = new ListToTable();
            ICourseRepository courseRepository = new CourseRepository();
            var       lst = courseRepository.GetCourseList().Select(x => new { x.CourseName, x.Id }).ToList();
            DataTable dt  = lsttodt.ToDataTable(lst);

            if (dt != null && dt.Rows.Count > 0)
            {
                ddCourse.DataSource     = dt;
                ddCourse.DataTextField  = "CourseName";
                ddCourse.DataValueField = "Id";
                ddCourse.DataBind();
            }
            else
            {
                ddCourse.DataBind();
            }
        }
コード例 #32
0
        public ActionResult Delete(string id)
        {
            var courseRepository = new CourseRepository(_context);
            var uploader         = new ImageUploader();
            var course           = courseRepository.GetById(new Guid(id));

            using (var tx = new TransactionScope())
            {
                if (course.Image != null)
                {
                    uploader.DeleteFile(course.Image);
                }
                courseRepository.Delete(course.Id);
                _context.Save(_loggedUser);
                tx.Complete();
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #33
0
ファイル: CourseBll.cs プロジェクト: GuoQqizz/SmartChinese
        private void UpdateStatus(DtoCoursePricing price, int currentUser)
        {
            var course = CourseRepository.GetCourse(price.CourseId);

            if (course == null)
            {
                throw new AbhsException(
                          ErrorCodeEnum.NotFoundEntity,
                          AbhsErrorMsg.NotFoundEntity);
            }
            else
            {
                course.EnableAudit();
                course.Ycs_Status     = (int)price.NextStatus;
                course.Ycs_UpdateTime = Clock.Now;
                course.Ycs_Editor     = currentUser;
                CourseRepository.Update(course);
            }
        }
コード例 #34
0
        public ActionResult Edit(int?id)
        {
            var student   = StudentRepository.Get(id);
            var viewModel = new StudentVM();

            viewModel.Student = student;
            viewModel.SetCourseItems(CourseRepository.GetAll());

            if (student.Courses != null)
            {
                viewModel.SelectedCourseIds = student.Courses.Select(c => c.CourseId).ToList();
            }



            viewModel.SetMajorItems(MajorRepository.GetAll());

            return(View(viewModel));
        }
コード例 #35
0
        public async Task <IActionResult> Index(string name)
        {
            ICourseRepository courseRepository = new CourseRepository( );

            if (name != null)
            {
                var courses = await courseRepository.SearchForCourses(name);

                TempData["SearchString"] = name;

                return(View(courses));
            }
            else
            {
                var courses = await courseRepository.GetCourses( );

                return(View(courses));
            }
        }
コード例 #36
0
        public void CheckInsertCourse()
        {
            // Arrange
            Course            c = new Course();
            List <Course>     courseList = new List <Course>();
            ICourseRepository icr = new CourseRepository();
            int elemListBefore, elemListAfter;

            c.GetSetName        = "TestPredmet";
            c.GetSetDescription = "Test Opis";
            // Act
            courseList     = icr.GetAllCourses();
            elemListBefore = courseList.Count;
            icr.InsertCourse(c);
            courseList    = icr.GetAllCourses();
            elemListAfter = courseList.Count;
            // Assert
            Assert.AreEqual(elemListBefore, elemListAfter - 1);
        }
コード例 #37
0
        public async Task Handle_WhenUserDoesNotExists_ReturnErrorThatUserDoesNotExists()
        {
            var course    = new Course(Guid.NewGuid(), "Mathematics");
            var courseIds = new List <Guid>()
            {
                course.Id
            };

            CourseRepository.Setup(cr => cr.GetByCourseIdAsync(course.Id)).Returns(Task.FromResult(course));
            UserRepository.Setup(cr => cr.GetByUserIdAsync(It.IsAny <Guid>())).Returns(Task.FromResult <User>(null));

            var command = new WithdrawUserCommand()
            {
                CourseIds = courseIds, UserId = Guid.NewGuid()
            };
            var result = await WithdrawUserCommandHandler.Handle(command, CancellationToken.None);

            result.Should().Be(CommandResultStatus.NotFound);
        }
コード例 #38
0
        public ActionResult Add(StudentVM studentVM)
        {
            studentVM.Student.Courses = new List <Course>();
            var model = StudentRepository.GetAll();

            foreach (var id in studentVM.SelectedCourseIds)
            {
                studentVM.Student.Courses.Add(CourseRepository.Get(id));
            }

            studentVM.Student.Major             = MajorRepository.Get(studentVM.Student.Major.MajorId);
            studentVM.Student.StudentId         = model.Max(s => s.StudentId) + 1;
            studentVM.Student.Address           = new Address();
            studentVM.Student.Address.AddressId = studentVM.Student.StudentId;

            StudentRepository.Add(studentVM.Student);

            return(RedirectToAction("List"));
        }
コード例 #39
0
        public void CourseRepositoryTests_ExistingCoursesShouldBeDelete()
        {
            //Arrange
            var sut    = new CourseRepository();
            var course = new Course {
                Id = 1, Name = "Test Course"
            };

            sut.Add(course);

            //Act
            var toDelete = sut.GetById(course.Id);

            sut.Remove(toDelete);
            var afterDelete = sut.GetById(course.Id);

            //Assert
            afterDelete.Should().BeNull();
        }
コード例 #40
0
        public async Task GetByIdAsyncTest(IEnumerable <Course> data, int id, Course?expected)
        {
            // Arrange
            await using (ApplicationContext context = _contextFactory.CreateDbContext())
            {
                await context.Courses.AddRangeAsync(data);

                await context.SaveChangesAsync();
            }

            var loggerMock = new Mock <ILogger <CourseRepository> >();
            var repository = new CourseRepository(_contextFactory, loggerMock.Object);

            // Act
            Course?course = await repository.GetByIdAsync(id);

            // Assert
            Assert.That(course, Is.EqualTo(expected));
        }
コード例 #41
0
        public ActionResult EditStudent(int id)
        {
            var studentVM = new StudentVM();

            studentVM.SetCourseItems(CourseRepository.GetAll());
            studentVM.SetMajorItems(MajorRepository.GetAll());
            studentVM.SetStateItems(StateRepository.GetAll());
            studentVM.Student = StudentRepository.Get(id);

            if (studentVM.Student.Courses != null)
            {
                foreach (Course course in studentVM.Student.Courses)
                {
                    studentVM.SelectedCourseIds.Add(course.CourseId);
                }
            }

            return(View(studentVM));
        }
コード例 #42
0
        public ActionResult EditStudents(int id)
        {
            CourseRepository         courseRepository  = new CourseRepository();
            StudentRepository        studentRepository = new StudentRepository();
            AdminControllerStudentVM studentModel      = new AdminControllerStudentVM();
            Student student            = new Student();
            List <SelectListItem> List = new List <SelectListItem>();

            studentModel.CourseList = courseRepository.GetAll();

            foreach (var item in studentModel.CourseList)
            {
                List.Add(new SelectListItem()
                {
                    Text = item.Name, Value = item.Id.ToString()
                });
            }

            if (id > 0)
            {
                student = studentRepository.GetById(id);
                List    = List.Where(c => c.Text != student.Course.Name).ToList();
                studentModel.FirstName     = student.FirstName;
                studentModel.LastName      = student.LastName;
                studentModel.UserName      = student.UserName;
                studentModel.Password      = student.Password;
                studentModel.FacultyNumber = student.FacultyNumber;
                studentModel.CourseID      = student.CourseID;
                studentModel.isActive      = student.IsActive;
                studentModel.SelectedCurse = student.Course.Name;
                studentModel.Id            = id;
            }
            if (id == 0)
            {
                student.FirstName = studentModel.FirstName;
                student.LastName  = studentModel.LastName;
                student.UserName  = studentModel.UserName;
                student.Password  = studentModel.Password;
                student.CourseID  = studentModel.CourseID;
            }
            studentModel.CourseListItems = List;
            return(View(studentModel));
        }
コード例 #43
0
        public ActionResult Courses()
        {
            if (!AuthenticationManager.LoggedUser.GetType().BaseType.Equals(typeof(Teacher)))
            {
                return RedirectToAction("Default", "Login");
            }
            TeacherControllerCoursesVM model = new TeacherControllerCoursesVM();
            CourseRepository courseRepository = new CourseRepository();

            Teacher teacher = new Teacher();
            TeacherRepository teacherRepository = new TeacherRepository();
            teacher = teacherRepository.GetById(AuthenticationManager.LoggedUser.Id);

            List<CourseSubject> courseSubjectList = teacher.CourseSubject.ToList();
            List<int> courseSubjectsId = courseSubjectList.Select(cs => cs.CourseID).Distinct().ToList();
            List<Course> courseList = new List<Course>();
            foreach (var item in courseSubjectsId)
            {
                courseList.Add(courseRepository.GetById(item));
            }
            model.CourseList = courseList;
            return View(model);
        }
コード例 #44
0
ファイル: Global.asax.cs プロジェクト: mikejwis/BuckeyeGolf
        protected void Application_Start()
        {
            Database.SetInitializer<GolfDbContext>(new GolfLeagueInitializer());
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var dbContext = new GolfDbContext();
            var configSettings = new ConfigRepository(dbContext).Get();
            Application.Add("HandicapWeeks", configSettings.HandicapWeekCount);
            Application.Add("HandicapRoundAdj", configSettings.RoundAdjustment);
            Application.Add("RoundParFront", configSettings.RoundParFront);
            Application.Add("RoundParBack", configSettings.RoundParBack);

            var courseSettings = new CourseRepository(dbContext).Get();
            var parRepo = new ParRespository(dbContext);
            var frontPars = parRepo.GetFrontPars(courseSettings.CourseId);
            var backPars = parRepo.GetBackPars(courseSettings.CourseId);
            Application.Add("FrontPars", frontPars);
            Application.Add("BackPars", backPars);
        }
コード例 #45
0
        // GET: Student2
        public ActionResult Create()
        {
            Student2ViewModel objEntity = new Student2ViewModel();

            #region DatabaseDropdown
            var objCourseRepository = new CourseRepository();
            var objCourseViewModelEntity = objCourseRepository.Select(CourseFlags.SelectAll.GetHashCode(), new CourseViewModel());
            objEntity.CourseList = new SelectList(objCourseViewModelEntity.Select(model => new { model.CourseId, model.CourseTitle }), "CourseId", "CourseTitle");
            #endregion

            #region DatabaseOptionGroup

            CountryStateRepository objCountryStateRepository = new CountryStateRepository();
            var objCountryStateEntityList = objCountryStateRepository.Select(CountryStateFlags.SelectAllForOptionGroup.GetHashCode(), new CountryStateViewModel());
            objEntity.SelectCountryList = new SelectList(objCountryStateEntityList, "StateId", "StateName", "CountryName", 1);
            #endregion

            objEntity.CurrentDate = DateTime.Now;

            objEntity.CurrentDateTime = DateTime.Now;

            return View(objEntity);
        }
コード例 #46
0
        public ActionResult AddSubject(int id, int[] subjectID, string Choose)
        {
            UnitOfWork unitOfWork = new UnitOfWork();
            CourseRepository courseRepo = new CourseRepository();
            CourseSubject cs = new CourseSubject();
            CourseSubjectRepository csRepo = new CourseSubjectRepository(unitOfWork);
            UserRepository<Teacher> teacherRepo = new UserRepository<Teacher>(unitOfWork);
            Teacher teacher = teacherRepo.GetAll(filter: t => t.ID == id).FirstOrDefault();

            int courseId = Convert.ToInt32(Choose);

            var curSubj = csRepo.GetAll(filter: x => x.CourseID == courseId && x.Teachers.Any(t => t.ID == id));

            try
            {
                foreach (var item in curSubj)
                {
                    teacher.CourseSubject.Remove(item);
                }
                if (subjectID != null)
                {
                    foreach (var item in subjectID)
                    {
                        cs = csRepo.GetAll(filter: c => c.SubjectID == item && c.CourseID == courseId).FirstOrDefault();
                        teacher.CourseSubject.Add(cs);
                    }
                }
                teacherRepo.Save(teacher);
                unitOfWork.Commit();
            }
            catch (Exception)
            {
                unitOfWork.RollBack();
            }

            return RedirectToAction("ListTeachers", "Teacher");
        }
コード例 #47
0
        public void CanGet()
        {
            _testDatabase.RunAndRollback(dbContext =>
            {
                var course1 = new Course
                {
                    Name = "Snijden"
                };

                var course2 = new Course
                {
                    Name = "Bakken"
                };

                dbContext.Courses.Add(course1);
                dbContext.Courses.Add(course2);
                dbContext.SaveChanges();

                var course = new CourseRepository(dbContext).Get(course2.Id);

                Assert.NotNull(course);
                Assert.Equal(course2.Id, course.Id);
            });
        }
コード例 #48
0
        public ActionResult CreateStudent(int? id)
        {
            StudentCreateStudentVM model = new StudentCreateStudentVM();
            CourseRepository cRepo = new CourseRepository();
            List<SelectListItem> list = new List<SelectListItem>();

            if (id != null)
            {
                var courses = cRepo.GetAll(filter: c => c.ID == id.Value).FirstOrDefault();
                list.Add(new SelectListItem() { Text = courses.Name + " || " + courses.FKNumber, Value = courses.ID.ToString() });
            }
            else
            {
                var courses = cRepo.GetAll();

                foreach (var item in courses)
                {
                    list.Add(new SelectListItem() { Text = item.Name + " || " + item.FKNumber, Value = item.ID.ToString() });
                }
            }

            model.CoursesList = list;
            return View(model);
        }
コード例 #49
0
        public ActionResult Report(string strFromDate, string strToDate, int filterId = 0)
        {
            Student2ViewModel objEntity = new Student2ViewModel();
            var objStudent2Repository = new Student2Repository();
            objEntity.Student2ReportList = new List<Student2ViewModel>();

            if (string.IsNullOrEmpty(strFromDate))
            {
                objEntity.FromDate = null;

            }
            else
            {
                objEntity.strFromDate = strFromDate;
                objEntity.FromDate = Convert.ToDateTime(strFromDate);
            }
            if (string.IsNullOrEmpty(strToDate))
            {
                objEntity.ToDate = null;

            }
            else
            {
                objEntity.strToDate = strToDate;
                objEntity.ToDate = Convert.ToDateTime(strToDate);
            }

            objEntity.CourseId = filterId;
            objEntity.filterId = filterId;

            #region DatabaseDropdown

            var objCourseRepository = new CourseRepository();
            var objCourseViewModelEntity = objCourseRepository.Select(CourseFlags.SelectAll.GetHashCode(), new CourseViewModel());
            objEntity.CourseList = new SelectList(objCourseViewModelEntity.Select(model => new { model.CourseId, model.CourseTitle }), "CourseId", "CourseTitle");

            #endregion

            if (objEntity.FromDate.HasValue && objEntity.ToDate.HasValue && objEntity.FromDate > objEntity.ToDate)
            {
                this.Flash("Warning", "From Date is smaller than To Date.");
                return View(objEntity);

            }

            objEntity.Student2ReportList = objStudent2Repository.Report(StudentFlags.SelectAllByReport.GetHashCode(), objEntity);

            if (objEntity.Student2ReportList.Count == 0 && (!string.IsNullOrEmpty(strFromDate) || !string.IsNullOrEmpty(strToDate) || filterId > 0))
            {
                this.Flash("Warning", "No matching records found.");
            }

            return View(objEntity);
        }
コード例 #50
0
 public DomainCourseService(CourseRepository courseRepository, CourseTakenRepository courseTakenRepository)
 {
     this.courseRepository = courseRepository;
     this.courseTakenRepository = courseTakenRepository;
 }
コード例 #51
0
        public ActionResult CreateStudent(StudentCreateStudentVM model, int? id)
        {
            Student student = new Student();
            Course course = new Course();
            UnitOfWork unitOfWork = new UnitOfWork();
            UserRepository<Student> sRepo = new UserRepository<Student>();
            CourseRepository courseRepo = new CourseRepository();

            if (!ModelState.IsValid)
            {
                List<SelectListItem> list = new List<SelectListItem>();
                if (id != null)
                {
                    var courses = courseRepo.GetAll(filter: c => c.ID == id.Value).FirstOrDefault();
                    list.Add(new SelectListItem() { Text = courses.Name + " || " + courses.FKNumber, Value = courses.ID.ToString() });
                }
                else
                {
                    var courses = courseRepo.GetAll();

                    foreach (var item in courses)
                    {
                        list.Add(new SelectListItem() { Text = item.Name + " || " + item.FKNumber, Value = item.ID.ToString() });
                    }
                }
                model.CoursesList = list;

                return View(model);
            }

            int courseID = Convert.ToInt32(model.selectedValueID);
            course = courseRepo.GetAll(filter: c => c.ID == courseID).FirstOrDefault();

            var fkNumberCount = (from t in sRepo.GetAll(filter: x => x.FacultiNumber.Contains(course.FKNumber)).OrderByDescending(s => s.FacultiNumber)
                                 select t).FirstOrDefault();

            student.FirstName = model.FirstName;
            student.LastName = model.LastName;

            if (fkNumberCount == null)
            {
                student.FacultiNumber = (Convert.ToInt32(course.FKNumber) * 1000 + 1).ToString();
            }
            else
            {
                student.FacultiNumber = (Convert.ToInt32(fkNumberCount.FacultiNumber) + 1).ToString();
            }

            student.CourseID = courseID;
            student.Active = true;
            Passphrase hash = PasswordHasher.Hash("password");
            student.Hash = hash.Hash;
            student.Salt = hash.Salt;

            student.Username = "******" + student.FacultiNumber;

            sRepo.Save(student);
            if (id != null)
            {
                return RedirectToAction("CreateStudent", "Student", new { id = id });
            }
            return RedirectToAction("ListStudents", "Student");
        }
コード例 #52
0
 public UnitOfWork(PlutoContext context)
 {
     _context = context;
     Courses = new CourseRepository(_context);
     Authors = new AuthorRepository(_context);
 }
コード例 #53
0
        public ActionResult EditStudent(int? id)
        {
            StudentEditStudentVM model = new StudentEditStudentVM();
            UserRepository<Student> stuRepo = new UserRepository<Student>();
            CourseRepository cRepo = new CourseRepository();

            Student student = stuRepo.GetByID(id.Value);

            var courses = cRepo.GetAll();

            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem() { Text = student.Course.Name + " || " + student.Course.FKNumber, Value = student.Course.ID.ToString() });
            foreach (var item in courses)
            {
                if (item.ID != student.Course.ID)
                {
                    list.Add(new SelectListItem() { Text = item.Name + " || " + item.FKNumber, Value = item.ID.ToString() });
                }
            }

            model.StudentID = student.ID;
            model.CourseID = student.CourseID;
            model.FirstName = student.FirstName;
            model.LastName = student.LastName;
            model.Active = student.Active;
            model.CoursesList = list;

            return View(model);
        }
コード例 #54
0
        public ActionResult EditStudent(StudentEditStudentVM model)
        {
            CourseRepository courseRepo = new CourseRepository();

            if (!ModelState.IsValid)
            {
                List<SelectListItem> list = new List<SelectListItem>();
                var courses = courseRepo.GetAll();

                foreach (var item in courses)
                {
                    list.Add(new SelectListItem() { Text = item.Name + " || " + item.FKNumber, Value = item.ID.ToString() });
                }

                model.CoursesList = list;
                return View(model);
            }
            UserRepository<Student> stuRepo = new UserRepository<Student>();
            Student student = new Student();
            Course course = new Course();

            student = stuRepo.GetByID(model.StudentID);

            int courseID = Convert.ToInt32(model.selectedValueID);
            if (model.CourseID != courseID)
            {
                course = courseRepo.GetAll(filter: c => c.ID == courseID).FirstOrDefault();
                var fkNumberCount = (from t in stuRepo.GetAll(filter: x => x.FacultiNumber.Contains(course.FKNumber)).OrderByDescending(s => s.FacultiNumber)
                                     select t).FirstOrDefault();

                if (fkNumberCount == null)
                {
                    student.FacultiNumber = (Convert.ToInt32(course.FKNumber) * 1000 + 1).ToString();
                }
                else
                {
                    student.FacultiNumber = (Convert.ToInt32(fkNumberCount.FacultiNumber) + 1).ToString();
                }
                student.CourseID = courseID;
            }
            student.FirstName = model.FirstName;
            student.Username = "******" + student.FacultiNumber;
            student.LastName = model.LastName;
            student.Active = model.Active;
            stuRepo.Save(student);

            return RedirectToAction("ListStudents", "Student");
        }
コード例 #55
0
        private void Init()
        {
            _studentRepo = new StudentRepository(_dbProvider);
            _courseRepo = new CourseRepository(_dbProvider);
            _courseRosterRepo = new CourseRosterRepository(_dbProvider);
            _emailRepo = new EmailRepository(_dbProvider);

            _coureCodeCache = new CourseCodeCache(_dbProvider);
            _semesterCache = new SemesterCache(_dbProvider);

            _coureCodeCache.Refresh();
            _semesterCache.Refresh();
        }
コード例 #56
0
 public CoursesController(CourseRepository courseRepository, CourseService courseService)
 {
     this.courseRepository = courseRepository;
     this.courseService = courseService;
 }
        public new void LoadChart(UserModel currentUser)
        {
            try
            {
                this.DrillChartIds = (this.DrillOverride) ? this.Id.ToString() : this.DrillChartIds;
                int colorIndex = 0;
                SandlerModels.DataIntegration.DataQueries queries = new SandlerModels.DataIntegration.DataQueries();
                AppointmentSourceRepository appointmentSource = null;
                ProductTypesRepository productTypesSource = null;
                string[] colors = null;
                string searchForNewCompany, searchCompanies;
                var totalPrice = 0.0;
                var totalCounts = 0.0;
                IEnumerable<Tbl_ProductType> products;
                string companyName = "";
                string franchiseeName = "";
                string regionName = "";
                string countryName = "";
                int monthToProcess, yearToProcess;
                double avgValue;
                switch (this.Id)
                {
                    case ChartID.SalesCycleTimeMain:
                        IEnumerable<SandlerModels.DataIntegration.SalesCycleTimePortfolioVM> salesCyclePortfolio = queries.GetSalesCycleTimePortfolio(currentUser);
                        int totalCount = salesCyclePortfolio.Count();
                        if (salesCyclePortfolio != null)
                        {
                            var salesCycleData = from opportunity in salesCyclePortfolio
                                                 group opportunity by new { opportunity.MultipleOfSixVal }
                                                     into grp
                                                     select new { Legend = ChartHelper.GetSCTimeLegend(grp.Key.MultipleOfSixVal), Count = grp.Count() * 100 / totalCount };

                            colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };

                            foreach (var record in salesCycleData)
                            {
                                this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Legend, Value = record.Count.ToString() });
                                colorIndex++;
                            }

                        }
                        break;

                    #region AdHocReports logic
                    case ChartID.PipelineOpportunityAnalysisBySource:
                        if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                            this.Caption = "Sales Value Percentage By Product";
                        if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                            this.Caption = "Sales Quantity Percentage By Product";

                        if (this.SubType == ChartSubType.SalesValueOppSource)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOppSource)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        if (this.SubType == ChartSubType.SalesValueOpportunityType)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        IEnumerable<SandlerModels.DataIntegration.PipelineOppAnalysisVM> pipelineSalesVMCollection = queries.GetPipelineOpportunityAnalysis(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };
                        totalPrice = pipelineSalesVMCollection.Sum(r => r.AvgPrice);
                        totalCounts = pipelineSalesVMCollection.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OpprtunitySourceRepository().GetAll())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((pipelineSalesVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((pipelineSalesVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else
                        {
                            int tmpCount = 0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            tmpCount = pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName).Count;
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = ((tmpCount * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        //}
                        break;
                    case ChartID.ClosedSalesAnalysisBySource:
                        if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                            this.Caption = "Sales Value Percentage By Product";
                        if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                            this.Caption = "Sales Quantity Percentage By Product";

                        if (this.SubType == ChartSubType.SalesValueOppSource)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOppSource)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        if (this.SubType == ChartSubType.SalesValueOpportunityType)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        IEnumerable<SandlerModels.DataIntegration.ClosedSalesVM> productTypeVMCollection = queries.GetClosedSalesAnalysis(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };
                        totalPrice = productTypeVMCollection.Sum(r => r.AvgPrice);
                        totalCounts = productTypeVMCollection.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OpprtunitySourceRepository().GetAll())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((productTypeVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((productTypeVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((productTypeVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((productTypeVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else
                        {
                            int tmpCount = 0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productTypeVMCollection.Single(r => r.Name == record.ProductTypeName).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            tmpCount = productTypeVMCollection.Single(r => r.Name == record.ProductTypeName).Count;
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = ((tmpCount * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        //}
                        break;
                    #endregion

                    #region FranchiseeReports logic
                    case ChartID.NewAppointmentsBySource:
                        monthToProcess = DateTime.ParseExact(this.DrillBy, "MMM", null).Month;
                        yearToProcess =  (monthToProcess > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year;

                        //if (queries.GetNewAppointmentSource(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var NewAppointmentSource = from record in queries.GetNewAppointmentSource(currentUser, monthToProcess, yearToProcess)
                                                   select new { Category = record.SourceName, Count = record.Count };

                        totalCount = NewAppointmentSource.Sum(r => r.Count);

                        appointmentSource = new AppointmentSourceRepository();
                        foreach (var record in appointmentSource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (NewAppointmentSource.Single(r => r.Category == record.ApptSourceName) != null)
                                {
                                    avgValue = NewAppointmentSource.Single(r => r.Category == record.ApptSourceName).Count * 100;
                                    avgValue = Math.Round(avgValue/totalCount,2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ApptSourceName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;

                    case ChartID.NewClientByProductType:
                        //if (queries.GetNewClientsByProductType(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        monthToProcess = DateTime.ParseExact(this.DrillBy, "MMM", null).Month;
                        yearToProcess =  (monthToProcess > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year;

                        var NewClientsByProductType = from record in queries.GetNewClientsByProductType(currentUser,monthToProcess, yearToProcess )
                                                      select new { Category = record.ProductTypeName, Count = record.Count };
                        totalCount = NewClientsByProductType.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (NewClientsByProductType.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = NewClientsByProductType.Single(r => r.Category == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##")});
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;
                    case ChartID.NewClientQuantity:
                        //if (queries.NewClientsWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var NewClientsWithProductTypes = from record in queries.NewClientsWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                         select new { Category = record.ProductTypeName, Count = record.Count };

                        productTypesSource = new ProductTypesRepository();
                        totalCount = NewClientsWithProductTypes.Sum(r => r.Count);
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (NewClientsWithProductTypes.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = NewClientsWithProductTypes.Single(r => r.Category == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;

                    case ChartID.ContractPrice:

                        //if (queries.ContractPriceWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var ContractPriceWithProductTypes = from record in queries.ContractPriceWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                            select new { Category = record.ProductTypeName, AvgPrice = record.AvgPrice };

                        productTypesSource = new ProductTypesRepository();
                        totalPrice = ContractPriceWithProductTypes.Sum(r => r.AvgPrice);
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (ContractPriceWithProductTypes.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = ContractPriceWithProductTypes.Single(r => r.Category == record.ProductTypeName).AvgPrice * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;
                    case ChartID.HeadcountByCourse:
                        //if (queries.GetHeadcountByCourse(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var headCountsByCourse = from record in queries.GetHeadcountByCourse(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                 select new { Course = record.CourseName, Count = record.Count };
                        totalCount = headCountsByCourse.Sum(r => r.Count);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00" };

                        CourseRepository courseSource = new CourseRepository();
                        foreach (var record in courseSource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (headCountsByCourse.Single(r => r.Course == record.CourseName) != null)
                                {
                                    avgValue = headCountsByCourse.Single(r => r.Course == record.CourseName).Count * 100;
                                    avgValue = Math.Round(avgValue/totalCount,2);
                                    this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.CourseName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;
                    case ChartID.HeadcountByIndustry:
                        var data = from record in queries.GetHeadcountByIndustry(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                   select new { Industry = record.IndustryTypeName, Count = record.Count };
                        totalCount = data.Sum(r => r.Count);
                        colors = new string[] { "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00" };

                        IndustryTypeRepository industrySource = new IndustryTypeRepository();
                        foreach (var record in industrySource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (data.Single(r => r.Industry == record.IndustryTypeName) != null)
                                {
                                    avgValue = data.Single(r => r.Industry == record.IndustryTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.IndustryTypeName, Value =  avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;
                    #endregion

                    #region ProductsReports Logic
                    case ChartID.ProductMarginValue:
                        var productSalesValue = from record in queries.GetProductSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                        totalPrice = productSalesValue.Sum(r => r.Value);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productSalesValue.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productSalesValue.Single(r => r.Name == record.ProductTypeName).Value * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductSalesQty:
                        var productSalesQty = from record in queries.GetProductSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                              select new { Name = record.ProductTypeName, Count = record.Count };

                        totalPrice = productSalesQty.Sum(r => r.Count);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productSalesQty.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productSalesQty.Single(r => r.Name == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductFirstSalesValue:
                        var productFirstSalesValue = from record in queries.GetProductFirstSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                     select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                        totalPrice = productFirstSalesValue.Sum(r => r.Value);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productFirstSalesValue.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productFirstSalesValue.Single(r => r.Name == record.ProductTypeName).Value*100;
                                    avgValue = Math.Round(avgValue/totalPrice,2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductFirstSalesQty:
                        var productFirstSalesQty = from record in queries.GetProductFirstSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                   select new { Name = record.ProductTypeName, Count = record.Count };

                        totalPrice = productFirstSalesQty.Sum(r => r.Count);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productFirstSalesQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productFirstSalesQty.Single(r => r.Name == record.ProductTypeName).Count) / totalPrice) * 100).ToString() });
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductSalesByCompanyQuantity:
                        try
                        {
                            companyName = new CompaniesRepository().GetById(long.Parse(SearchParameter)).COMPANYNAME;
                            this.Caption = this.Caption.Replace("Company Name", companyName);
                            var productSalestoCompanyQty = from record in queries.GetProductSoldByCompanyByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, int.Parse(this.SearchParameter))
                                                           select new { Name = record.ProductTypeName, Count = record.Count };

                            totalCounts = productSalestoCompanyQty.Sum(r => r.Count);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            //double percentCount = 0.0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalestoCompanyQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalestoCompanyQty.Single(r => r.Name == record.ProductTypeName).Count) / totalCounts) * 100).ToString() });
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesByCompanyQuantity:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesByCompanyValue:
                        try
                        {
                            companyName = new CompaniesRepository().GetById(long.Parse(SearchParameter)).COMPANYNAME;
                            this.Caption = this.Caption.Replace("Company Name", companyName);
                            var productSalestoCompanyValue = from record in queries.GetProductSoldByCompanyByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, int.Parse(SearchParameter))
                                                             select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                            totalPrice = productSalestoCompanyValue.Sum(r => r.Value);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalestoCompanyValue.Single(r => r.Name == record.ProductTypeName) != null)
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalestoCompanyValue.Single(r => r.Name == record.ProductTypeName).Value) / totalPrice) * 100).ToString() });
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesByCompanyValue:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesBySalesRepQuantity:
                        try
                        {
                            this.Caption = this.Caption.Replace("Sales Rep", SearchParameter);
                            var productSalesBySalesRepQty = from record in queries.GetProductSoldBySalesRepByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SearchParameter)
                                                            select new { Name = record.ProductTypeName, Count = record.Count };

                            totalCounts = productSalesBySalesRepQty.Sum(r => r.Count);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            //double percentCount = 0.0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalesBySalesRepQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalesBySalesRepQty.Single(r => r.Name == record.ProductTypeName).Count) / totalCounts) * 100).ToString() });
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesBySalesRepQuantity:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesBySalesRepValue:
                        try
                        {
                            this.Caption = this.Caption.Replace("Sales Rep", SearchParameter);
                            var productSalesBtSalesRepValue = from record in queries.GetProductSoldBySalesRepByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, SearchParameter)
                                                              select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                            totalPrice = productSalesBtSalesRepValue.Sum(r => r.Value);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalesBtSalesRepValue.Single(r => r.Name == record.ProductTypeName) != null)
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalesBtSalesRepValue.Single(r => r.Name == record.ProductTypeName).Value) / totalPrice) * 100).ToString() });
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesBySalesRepValue:" + ex.Message);
                        }
                        break;
                    #endregion

                    #region BenchMarkReports Logic

                    case ChartID.BenchmarkSalesRepFranchiseeQty:
                        double salesRepQty;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(currentUser.FranchiseeID).Name;
                            Caption = Caption.Replace("Sales Rep", SearchParameter).Replace("Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRepToFranchiseeData = queries.GetBenchMarkSalesRepToFranchiseeByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesRepToFranchiseeData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((((from record in salesRepToFranchiseeData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM repRecord = salesRepToFranchiseeData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            salesRepQty = (repRecord == null) ? 0.0 : repRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "FF8C00",
                                Label = "Rep",
                                Value = (( salesRepQty/ totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkSalesRepFranchiseeQty:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkSalesRepFranchiseeValue:
                        double salesRepValue;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(currentUser.FranchiseeID).Name;
                            Caption = Caption.Replace("Sales Rep", SearchParameter).Replace("Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRepToFranchiseeData = queries.GetBenchMarkSalesRepToFranchiseeByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalPrice = salesRepToFranchiseeData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((((from record in salesRepToFranchiseeData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM repRecord = salesRepToFranchiseeData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            salesRepValue = (repRecord == null) ? 0.0 : repRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "FF8C00",
                                Label = "Rep",
                                Value = ((salesRepValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkSalesRepFranchiseeValue:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkFranchiseeRegionQty:
                        double franchiseeQty;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(int.Parse(SearchParameter)).Name;
                            regionName = new RegionRepository().GetById(currentUser.RegionID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Franchisee Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesFranchiseeToRegionsData = queries.GetBenchMarkFranchiseeToRegionsByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesFranchiseeToRegionsData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((((from record in salesFranchiseeToRegionsData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesFranchiseeToRegionsData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            franchiseeQty = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((franchiseeQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionQty:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkFranchiseeRegionValue:
                        double franchiseeValue;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(int.Parse(SearchParameter)).Name;
                            regionName = new RegionRepository().GetById(currentUser.RegionID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Franchisee Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesFranchiseeToRegionsData = queries.GetBenchMarkFranchiseeToRegionsByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalPrice = salesFranchiseeToRegionsData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((((from record in salesFranchiseeToRegionsData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesFranchiseeToRegionsData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            franchiseeValue = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((franchiseeValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionValue:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkRegionCountryQty:
                        double regionQty;
                        try
                        {
                            regionName = new RegionRepository().GetById(int.Parse(SearchParameter)).Name;
                            countryName = new CountryRepository().GetById(currentUser.CountryID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRegionToCountryData = queries.GetBenchMarkRegionToCountryByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesRegionToCountryData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "Country",
                                Value = ((((from record in salesRegionToCountryData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM regionRecord = salesRegionToCountryData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            regionQty = (regionRecord == null) ? 0.0 : regionRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((regionQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkRegionCountryQty:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkRegionCountryValue:
                        double regionValue;
                        try
                        {
                            regionName = new RegionRepository().GetById(int.Parse(SearchParameter)).Name;
                            countryName = new CountryRepository().GetById(currentUser.CountryID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Country Name", countryName);

                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRegionToCountryData = queries.GetBenchMarkRegionToCountryByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month);

                            totalPrice = salesRegionToCountryData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "Country",
                                Value = ((((from record in salesRegionToCountryData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM regionRecord = salesRegionToCountryData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            regionValue = (regionRecord == null) ? 0.0 : regionRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((regionValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionValue:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkCountryAllQty:
                        double countryQty;
                        try
                        {
                            countryName = new CountryRepository().GetById(int.Parse(SearchParameter)).Name;
                            Caption = Caption.Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesCountryAllData = queries.GetBenchMarkCountryAllByMonth( DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesCountryAllData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "All",
                                Value = ((((from record in salesCountryAllData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM countryRecord = salesCountryAllData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            countryQty = (countryRecord == null) ? 0.0 : countryRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "00CED1",
                                Label = "Country",
                                Value = ((countryQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkRegionCountryQty:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkCountryAllValue:
                        double countryValue;
                        try
                        {
                            countryName = new CountryRepository().GetById(int.Parse(SearchParameter)).Name;
                            Caption = Caption.Replace("Country Name", countryName);

                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesCountryAllData = queries.GetBenchMarkCountryAllByMonth( DateTime.ParseExact(this.DrillBy, "MMM", null).Month);

                            totalPrice = salesCountryAllData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "All",
                                Value = ((((from record in salesCountryAllData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM countryRecord = salesCountryAllData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            countryValue = (countryRecord == null) ? 0.0 : countryRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "00CED1",
                                Label = "Country",
                                Value = ((countryValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkCountryAllValue:" + ex.Message);
                        }
                        break;
                    #endregion

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #58
0
 public ActionResult Index()
 {
     if (AuthenticationManager.LoggedUser == null || !AuthenticationManager.LoggedUser.GetType().BaseType.Equals(typeof(Teacher)))
     {
         return RedirectToAction("Login", "Default");
     }
     TeacherControllerTeacherVM model = new TeacherControllerTeacherVM();
     Teacher teacher = new Teacher();
     TeacherRepository teacherRepository = new TeacherRepository();
     teacher = teacherRepository.GetById(AuthenticationManager.LoggedUser.Id);
     model.FirstName = teacher.FirstName;
     model.LastName = teacher.LastName;
     CourseSubjectRepository courseSubjectRepository = new CourseSubjectRepository();
     CourseRepository courseRepository = new CourseRepository();
     SubjectRepository subjectRepository = new SubjectRepository();
     List<int> subjectList = new List<int>();
     Dictionary<string, List<Subject>> courseSubjectList = new Dictionary<string, List<Subject>>();
     List<Subject> subjects = new List<Subject>();
     List<int> courseList = new List<int>();
     foreach (var courseSubject in teacher.CourseSubject)
     {
         courseList.Add(courseSubject.Course.Id);
         subjectList.Add(courseSubject.Subject.Id);
     }
     subjectList = subjectList.Distinct().ToList();
     courseList = courseList.Distinct().ToList();
     Course course = new Course();
     foreach (var courseID in courseList)
     {
         course = courseRepository.GetById(courseID);
         subjects = courseSubjectRepository.GetAll(filter: c => c.Course.Id == courseID && subjectList.Contains(c.Subject.Id)).Select(s => s.Subject).ToList();
         courseSubjectList.Add(course.Name, subjects);
     }
     model.CourseSubjectList = courseSubjectList;
     return View(model);
 }
コード例 #59
0
        public ActionResult Index()
        {
            StudentIndexVM model = new StudentIndexVM();
            UserRepository<Student> stuRepo = new UserRepository<Student>();
            CourseRepository courseRepo = new CourseRepository();
            GradeRepository gradeRepo = new GradeRepository();
            UserRepository<Teacher> teacherRepo = new UserRepository<Teacher>();

            Student student = stuRepo.GetByID(Models.AuthenticationManager.LoggedUser.ID);

            model.FacultiNumber = student.FacultiNumber;
            model.FirstName = student.FirstName;
            model.LastName = student.LastName;

            Course course = courseRepo.GetAll(filter: x => x.CourseSubject.Any(c => c.Course.Student.Any(s => s.ID == Models.AuthenticationManager.LoggedUser.ID))).FirstOrDefault();

            model.CourseName = course.Name;

            model.Grades = gradeRepo.GetAll(filter: g => g.StudentID == Models.AuthenticationManager.LoggedUser.ID);

            return View(model);
        }
コード例 #60
0
        public void CanUpdate()
        {
            _testDatabase.RunAndRollback(dbContext =>
            {
                var updatedName = "Koken";

                var course = new Course
                {
                    Name = "Snijden"
                };

                dbContext.Courses.Add(course);
                dbContext.SaveChanges();

                course.Name = updatedName;
                var updatedCourse = new CourseRepository(dbContext).Update(course);

                Assert.NotNull(updatedCourse);
                Assert.Equal(course.Id, updatedCourse.Id);
                Assert.Equal(updatedName, updatedCourse.Name);
            });
        }