コード例 #1
0
        public InstructorAssignment(Instructor teacher, SubjectDelivery subject)
        {
            Instructor = teacher as Teacher;
            Subject = subject;
            Role = InstructorAssignmentRole.All;

        }
コード例 #2
0
ファイル: Program.cs プロジェクト: jeanne27king/IT1050
        static void Main(string[] args)
        {
            //Create Instructor 
            Instructor John = new Instructor("John", "English");
            Instructor Mike = new Instructor("Mike", "Math");

            //Create Students
            Student Jane = new Student("Jane", John);
            Student Joe = new Student("Joe", John);
            Student Melissa = new Student("Melissa", Mike);
            Student Matt = new Student("Matt", Mike);

            //Instructor Set Student Grade
            John.StudentGrade(Jane, 95);
            John.StudentGrade(Joe, 85);
            Mike.StudentGrade(Melissa, 90);
            Mike.StudentGrade(Matt, 92);

            //Print Instructor Information
            John.PrintInstructorInfo();
            Mike.PrintInstructorInfo();

            //Print Student Information
            Jane.PrintStudentInfo();
            Joe.PrintStudentInfo();
            Melissa.PrintStudentInfo();
            Matt.PrintStudentInfo();

            System.Console.ReadKey();

        }
コード例 #3
0
ファイル: Program.cs プロジェクト: LaurenMazzoli/IT-1050
        static void Main(string[] args)
        {
            var john = new Instructor("John", "English");
            var mike = new Instructor("Mike", "Math");

            var jane = new Student("Jane", john);
            var joe = new Student("Joe", john);
            var melissa = new Student("Melissa", mike);
            var matt = new Student("Matt", mike);

            john.SetStudentGrade(jane, 95);
            john.SetStudentGrade(joe, 85);

            mike.SetStudentGrade(melissa, 90);
            mike.SetStudentGrade(matt, 92);

            Show.Divider();
            Show.Header();

            jane.PrintStudentInfo();
            joe.PrintStudentInfo();
            melissa.PrintStudentInfo();
            matt.PrintStudentInfo();

            Show.Divider();
            Show.ProgEnd();
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: Madhunayak/IT1050
        static void Main(string[] args)
        {
            Instructor John = new Instructor("John", "English");
            Instructor Mike = new Instructor("MIKE", "Math");

            Student Jane = new Student("Jane", John);
            Student Joe = new Student("Joe", John);

            Student Melissa = new Student("Melissa", Mike);
            Student Matt = new Student("Matt", Mike);

            John.SetStudentGrade(Jane, 95);
            John.SetStudentGrade(Joe, 85);
            Mike.SetStudentGrade(Melissa, 90);
            Mike.SetStudentGrade(Matt, 92);

            Jane.PrintStudentInfo();
            Joe.PrintStudentInfo();
            Melissa.PrintStudentInfo();
            Matt.PrintStudentInfo();

            System.Console.WriteLine();
            System.Console.ReadKey();


        }
コード例 #5
0
ファイル: Program.cs プロジェクト: hannah-purgar/IT-1025
        static void Main(string[] args)
        {

            //     INSTUCTOR CREATION     //
            Instructor john = new Instructor("John", "English");
            Instructor mike = new Instructor("Mike", "Math");
            
            //     STUDENT CREATION     //
            Student jane = new Student("Jane", john);
            Student joe = new Student("Joe", john);
            Student melissa = new Student("Melissa", mike);
            Student matt = new Student("Matt", mike);

            //     GRADE ASSIGNMENT     //
            john.SetGrade(jane, 95);
            john.SetGrade(joe, 85);
            mike.SetGrade(melissa, 90);
            mike.SetGrade(matt, 92);

            jane.Print();
            joe.Print();
            melissa.Print();
            matt.Print();
            System.Console.Read();

        }
コード例 #6
0
 // GET: Instructor/Create
 public ActionResult Create()
 {
     var instructor = new Instructor();
     instructor.Courses = new List<Course>();
     PopulateAssignedCourseData(instructor);
     return View();
 }
コード例 #7
0
ファイル: Program.cs プロジェクト: kcbwilson/IT-1050
        static void Main(string[] args)
        {
            Instructor EnglishInstructor = new Instructor("John", "English");

            Instructor MathInstructor = new Instructor("Mike", "Math");

            Student Student1 = new Student("Jane", EnglishInstructor);

            Student Student2 = new Student("Joe", EnglishInstructor);

            Student Student3 = new Student("Melissa", MathInstructor);

            Student Student4 = new Student("Matt", MathInstructor);

            EnglishInstructor.SetStudentGrade(Student1, 95);
            EnglishInstructor.SetStudentGrade(Student2, 85);
            MathInstructor.SetStudentGrade(Student3, 90);
            MathInstructor.SetStudentGrade(Student4, 92);

            System.Console.WriteLine("    Student Information    ");
            System.Console.WriteLine(" ");
            Student1.Print();
            Student2.Print();
            Student3.Print();
            Student4.Print();
            System.Console.ReadKey();
        }
コード例 #8
0
        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (PasswordBox.Password != PasswordRepeatBox.Password)
                    throw new Exception("Паролі не співпадають");
                Instructor instructor = new Instructor(LoginBox.Text, PasswordBox.Password, FirstNameBox.Text, LastNameBox.Text,
                    SecondNameBox.Text);
                Configuration config = (App.Current as App).config;
                using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port))
                {
                    using (NetworkStream writerStream = eClient.GetStream())
                    {
                        MSG message = new MSG();
                        message.stat = STATUS.ADD_INSTRUCTOR;
                        BinaryFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(writerStream, message);
                        formatter.Serialize(writerStream, instructor);
                        bool fl = (bool)formatter.Deserialize(writerStream);
                        if (!fl)
                            MessageBox.Show("Помилка додавання облікового запису");
                        else
                        {
                            NavigationService nav = NavigationService.GetNavigationService(this);
                            nav.Navigate(new System.Uri("StartPage.xaml", UriKind.RelativeOrAbsolute));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
コード例 #9
0
        static void Main(string[] args)
        {
            Instructor johnh = new Instructor("johnh", "english");
            Instructor mike = new Instructor("Mike", "Math");
            Student jane = new Student("Jane", johnh,0);
            Student joe = new Student("Joe", johnh,0);
            Student melissa = new Student("Melisa", mike,0);
            Student matt = new Student("Matt", mike,0);
            /////////////////////////////////////////////////////////

            johnh.SetStudetGrade(jane, 95);
            johnh.SetStudetGrade(joe, 85);
            mike.SetStudetGrade(melissa, 90);
            mike.SetStudetGrade(matt, 92);
            /////////////////////////////////////////////////////////
            melissa.PrintNameGradeTeacher();
            jane.PrintNameGradeTeacher();
            joe.PrintNameGradeTeacher();
            matt.PrintNameGradeTeacher();
            //////////////////////////////////////////////////
            //johnh.PrintTeacherInformation();
            //mike.PrintTeacherInformation();
            System.Console.WriteLine("press any key to end.. ");
            System.Console.ReadKey();
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: aasante0619/Class-IT1050
        static void Main(string[] args)
        {
            Instructor John = new Instructor("John", "Smith", "English");

            John.PrintInfo();

               Instructor Mike = new Instructor("Mike", "Jones", "Math");
            Mike.PrintInfo();

            Student Jane = new Student("Jane", "Adams", John, 0);
            Student Joe = new Student("Joe", "Jenkins", John, 0);
            Student Melissa = new Student("Melissa", "King", Mike, 0);
            Student Matt = new Student("Matt", "Sanchez", Mike, 0);

            John.SetStudentGrade(Jane, 95);
            John.SetStudentGrade(Joe, 85);
            Mike.SetStudentGrade(Melissa, 90);
            Mike.SetStudentGrade(Matt, 92);

            Jane.PrintNameTeacherCourse();

            Joe.PrintNameTeacherCourse();

            Melissa.PrintNameTeacherCourse();

            Matt.PrintNameTeacherCourse();

            System.Console.ReadKey();
        }
コード例 #11
0
ファイル: Student.cs プロジェクト: aasante0619/Class-IT1050
 public Student(string studentFirstName, string studentLastName, Instructor Teacher, int Grade)
 {
     this.FirstName = studentFirstName;
     this.LastName = studentLastName;
     this.fullname = this.FirstName + " " + this.LastName;
     this.Teacher = Teacher;
     this.Grade = Grade;
 }
コード例 #12
0
 // GET: Instructor/Create
 public ActionResult Create()
 {
     //ViewBag.ID = new SelectList(db.OfficeAssignments, "InstructorID", "Location");
     var instructor = new Instructor();
     instructor.Courses = new List<Course>();
     PopulateAssignedCourseData(instructor);
     return View();
 }
コード例 #13
0
        /// <summary>
        /// Prevents a default instance of the <see cref="WarriorTrainer" /> class from being created.
        /// </summary>
        /// <param name="i2">The i2.</param>
        private WarriorTrainer(Instructor i2)
        {
            i = i2;

            a = 1;
            d = 1;
            h = 1;
        }
コード例 #14
0
ファイル: GameManager.cs プロジェクト: ChrisMaire/surfenstein
 void Awake()
 {
     effects = GameObject.FindObjectOfType<EffectPlayer>();
     pieces = GameObject.FindObjectsOfType<MoveForward>().ToList();
     player = GameObject.FindObjectOfType<Player>();
     music = GetComponent<MusicManager>();
     score = GetComponent<ScoreManager>();
     instructor = GameObject.FindObjectOfType<Instructor>();
     obstacles = GameObject.Find("Obstacle");
 }
コード例 #15
0
        public ActionResult Create(Instructor instructor)
        {
            if (RepositoryFactory.InstructorRepository.Queryable.Any(i => i.Identifier == instructor.Identifier))
            {
                Message =
                    string.Format(
                        "Instructor could not be created because an instructor with the identifier {0} already exists",
                        instructor.Identifier);
                return RedirectToAction("Index");
            }

            var instructorToCreate = new Instructor();

            TransferValues(instructor, instructorToCreate);

            if (ModelState.IsValid)
            {
                //if the instructor doesn't exist as a user account, create them an account and profile
                var existingUser =
                    RepositoryFactory.UserRepository.Queryable.SingleOrDefault(
                        x => x.Identifier == instructorToCreate.Identifier);

                if (existingUser == null)
                {
                    var profile = new Profile
                        {
                            FirstName = instructorToCreate.FirstName,
                            LastName = instructorToCreate.LastName,
                            Email = instructorToCreate.Identifier,
                            ImageUrl = WebConfigurationManager.AppSettings["DefaultProfilePictureUrl"]
                        };

                    var user = new User {Identifier = instructorToCreate.Identifier};
                    user.AssociateProfile(profile);
                    user.Roles.Add(RepositoryFactory.RoleRepository.GetById(RoleNames.Instructor));
                    existingUser = user;
                    RepositoryFactory.UserRepository.EnsurePersistent(user);
                }

                instructorToCreate.User = existingUser;
                RepositoryFactory.InstructorRepository.EnsurePersistent(instructorToCreate);

                Message = "Instructor Created Successfully";

                return RedirectToAction("Index");
            }
            else
            {
                var viewModel = InstructorViewModel.Create(Repository);
                viewModel.Instructor = instructor;

                return View(viewModel);
            }
        }
コード例 #16
0
 public void UpdateInstructor(Instructor instructor)
 {
     //try
     //{
         context.Entry(instructor).State = EntityState.Modified;
     //}
     //catch
     //{
     //    throw;
     //}
 }
コード例 #17
0
        public ActionResult Create(Instructor instructor)
        {
            if (ModelState.IsValid)
            {
                db.Instructors.Add(instructor);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CourseId = new SelectList(db.Courses, "CourseID", "CourseName", instructor.CourseId);
            return View(instructor);
        }
コード例 #18
0
ファイル: InstructorController.cs プロジェクト: joeya/MVCDEMO
        public ActionResult Create(Instructor instructor)
        {
            if (ModelState.IsValid)
            {
                db.Instructors.Add(instructor);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.PersonID = new SelectList(db.OfficeAssignments, "PersonID", "Location", instructor.PersonID);
            return View(instructor);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: killingerr/Rosella
        static void Main(string[] args)
        {
            //Class objects creation from base and derived classes
            Person myPerson = new Person("Tony", "Rosella" ,"123 way St.", "444-5555");
            Student myStudent = new Student("Joe", "Bob", "321 North Ave.", "321-123-4567", 3.45, "Computer Science", "11/10/16");
            Employee myEmployee = new Employee("Jake", "Smith", "456 Sea Dr.", "321-867-5309", "42345", "Health");
            Instructor myInstructor = new Instructor("Shela", "Roberts", "323 Fruit way", "323-456-3412", "333", "8-4 pm");

            //Displays info for each class
            Console.WriteLine(myPerson);
            Console.WriteLine(myStudent);
            Console.WriteLine(myEmployee);
            Console.WriteLine(myInstructor);
        }
コード例 #20
0
        public static EntityStateWrapperContainer Create(IQueryRepository queryRepository, CreateInstructorWithCourses.CommandModel commandModel)
        {
            // could use Course.CreatePartial here and attachEntities using EntityStateWrapperContainer
            var courses = commandModel.SelectedCourses == null
                ? new Course[0].ToList()
                : queryRepository.GetEntities<Course>(new FindByIdsSpecificationStrategy<Course>(p => p.CourseID, commandModel.SelectedCourses)).ToList();

            var instructor = new Instructor
            {
                HireDate = commandModel.HireDate,
                FirstMidName = commandModel.FirstMidName,
                LastName = commandModel.LastName,
                Courses = courses,
                OfficeAssignment = new OfficeAssignment { Location = commandModel.OfficeLocation },
            };

            return new EntityStateWrapperContainer().AddEntity(instructor);
        }
コード例 #21
0
ファイル: DBProvider.cs プロジェクト: Timothyyy/ICS_MSHRC
 public static void AddInstructor(Instructor instructor)
 {
     using (var conn = new SQLiteConnection(ConnectionString))
     {
         conn.Open();
         var cmd = new SQLiteCommand("insert into Instructors" + Instparam, conn);
         cmd.Parameters.AddWithValue("@1", instructor.FullName);
         cmd.Parameters.AddWithValue("@2", instructor.Sex);
         cmd.Parameters.AddWithValue("@3", instructor.Address);
         cmd.Parameters.AddWithValue("@4", instructor.Phone);
         cmd.Parameters.AddWithValue("@5", instructor.Email);
         cmd.Parameters.AddWithValue("@6", instructor.Education);
         cmd.Parameters.AddWithValue("@7", instructor.Department);
         cmd.Parameters.AddWithValue("@8", instructor.Post);
         cmd.Parameters.AddWithValue("@9", instructor.Start);
         cmd.Parameters.AddWithValue("@10", instructor.Other);
         cmd.ExecuteNonQuery();
     }
 }
コード例 #22
0
ファイル: Program.cs プロジェクト: Neishafannin/MyStuff
        static void Main(string[] args)
        {
            Instructor person1 = new Instructor("John", "English");
            Instructor person2 = new Instructor("Mike", "Math");

            Student student1 = new Student("Jane", person1);
            Student student2 = new Student("Joe", person1);
            Student student3 = new Student("Melissa", person2);
            Student student4 = new Student("Matt", person2);

            person1.SetStudentGrade(student1, 95);
            person1.SetStudentGrade(student2, 85);
            person2.SetStudentGrade(student3, 90);
            person2.SetStudentGrade(student4, 92);

            student1.Print();
            student2.Print();
            student3.Print();
            student4.Print();
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: Owaldi/IT1050
        static void Main(string[] args)
        {
            Instructor John = new Instructor("John", "English");
            Instructor Mike = new Instructor("Mike", "Math");

            Student Jane = new Student("Jane", John);
            Student Joe = new Student("Joe", John);
            Student Melissa = new Student("Melissa", Mike);
            Student Matt = new Student("Matt", Mike);

            // Write some more code!

            //John.SetStudentGrade(Jane, 96);
            //John.SetStudentGrade(Joe, 85);
            //Mike.SetStudentGrade(Melissa, 90);
            //Mike.SetStudentGrade(Matt, 92);

            //Jane.PrintNameGradeAndTeacher();
            //Joe.PrintNameGradeAndTeacher();
            //Melissa.PrintNameGradeAndTeacher();
            //Matt.PrintNameGradeAndTeacher();
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: bbosowski6690/IT-1050
        static void Main(string[] args)
        {
            Instructor John = new Instructor("John", "Smith", "English");

               Instructor Mike = new Instructor("Mike", "Thornton", "Math");

            John.SetStudentGrade("Jane", 95);
            John.SetStudentGrade("Joe", 85);
            Mike.SetStudentGrade("Melissa", 90);
            Mike.SetStudentGrade("Matt", 92);

            Student Jane = new Student("Jane", 0, John);
            Jane.Print();

            Student Joe = new Student("Joe", 0, John);
            Joe.Print();

            Student Melissa = new Student("Melissa", 0, Mike);
            Melissa.Print();

            Student Matt = new Student("Matt", 0, Mike);
            Matt.Print();

            System.Console.ReadKey();

            //Write your “main” method in Program.cs according to the following pseudocode:
            //Create an Instructor named “John” who teaches “English”.
            //Create an Instructor named “Mike” who teaches “Math”.
            //Create a Student named “Jane” whose teacher is John.
            //Create a Student named “Joe” whose teacher is John.
            //Create a Student named “Melissa” whose teacher is Mike.
            //Create a Student named “Matt” whose teacher is Mike.
            //Have John give Jane a grade of 95.
            //Have John give Joe a grade of 85.
            //Have Mike give Melissa a grade of 90.
            //Have Mike give Matt a grade of 92.
            //Have every student Print their information.
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: JennJackson/IT-1050
        static void Main(string[] args)
        {
            // Program purpose:
            // Creates new Instructor objects
            // Creates new Student objects
            // Instructors can set their students' grades
            // Student info prints out to the screen after entering grades
            
            Instructor instructor1 = new Instructor("John", "English");
            Instructor instructor2 = new Instructor("Mike", "Math");

            Student student1 = new Student("Jane", instructor1);
            Student student2 = new Student("Joe", instructor1);
            Student student3 = new Student("Melissa", instructor2);
            Student student4 = new Student("Matt", instructor2);

            instructor1.SetStudentGrade(student1, 95);
            instructor1.SetStudentGrade(student2, 85);
            instructor2.SetStudentGrade(student3, 90);
            instructor2.SetStudentGrade(student4, 92);

            System.Console.WriteLine("Press any key to continue...");
            System.Console.ReadKey();
        }
コード例 #26
0
        // GET: Instructors/Details/5
        public ActionResult Details(int id)
        {
            Instructor instructor = GetInstructorById(id);

            return(View(instructor));
        }
コード例 #27
0
        private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
        {
            if (selectedCourses == null)
            {
                instructorToUpdate.Courses = new List<Course>();
                return;
            }

            var selectedCoursesHS = new HashSet<string>(selectedCourses);
            var instructorCourses = new HashSet<int>
                (instructorToUpdate.Courses.Select(c => c.CourseID));
            foreach (var course in db.Courses)
            {
                if (selectedCoursesHS.Contains(course.CourseID.ToString()))
                {
                    if (!instructorCourses.Contains(course.CourseID))
                    {
                        instructorToUpdate.Courses.Add(course);
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.CourseID))
                    {
                        instructorToUpdate.Courses.Remove(course);
                    }
                }
            }
        }
コード例 #28
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var departmentToUpdate = await _context.Departments.Include(i => i.Administrator).SingleOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes. The department was deleted by another user.");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    // Using a NoTracking query means we get the entity but it is not tracked by the context
                    // and will not be merged with existing entities in the context.
                    var databaseEntity = await _context.Departments
                                         .AsNoTracking()
                                         .SingleAsync(d => d.DepartmentID == ((Department)exceptionEntry.Entity).DepartmentID);

                    var databaseEntry = _context.Entry(databaseEntity);

                    var databaseName = (string)databaseEntry.Property("Name").CurrentValue;
                    var proposedName = (string)exceptionEntry.Property("Name").CurrentValue;
                    if (databaseName != proposedName)
                    {
                        ModelState.AddModelError("Name", $"Current value: {databaseName}");
                    }
                    var databaseBudget = (Decimal)databaseEntry.Property("Budget").CurrentValue;
                    var proposedBudget = (Decimal)exceptionEntry.Property("Budget").CurrentValue;
                    if (databaseBudget != proposedBudget)
                    {
                        ModelState.AddModelError("Budget", $"Current value: {databaseBudget:c}");
                    }
                    var databaseStartDate = (DateTime)databaseEntry.Property("StartDate").CurrentValue;
                    var proposedStartDate = (DateTime)exceptionEntry.Property("StartDate").CurrentValue;
                    if (databaseStartDate != proposedStartDate)
                    {
                        ModelState.AddModelError("StartDate", $"Current value: {databaseStartDate:d}");
                    }
                    var databaseInstructorID = (int)databaseEntry.Property("InstructorID").CurrentValue;
                    var proposedInstructorID = (int)exceptionEntry.Property("InstructorID").CurrentValue;
                    if (databaseInstructorID != proposedInstructorID)
                    {
                        Instructor databaseInstructor = await _context.Instructors.SingleAsync(i => i.ID == databaseInstructorID);

                        ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor.FullName}");
                    }

                    ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                             + "was modified by another user after you got the original value. The "
                                             + "edit operation was canceled and the current values in the database "
                                             + "have been displayed. If you still want to edit this record, click "
                                             + "the Save button again. Otherwise click the Back to List hyperlink.");
                    departmentToUpdate.RowVersion = (byte[])databaseEntry.Property("RowVersion").CurrentValue;
                    ModelState.Remove("RowVersion");
                }
            }
            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
コード例 #29
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var departmentToUpdate = await _context.Departments.Include(i => i.Administrator).SingleOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save change");
                    }
                    else
                    {
                        var databaseValues = (Department)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", $"Current value: {databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValues.Budget)
                        {
                            ModelState.AddModelError("Budget", $"Current value: {databaseValues.Budget:c}");
                        }
                        if (databaseValues.StartDate != clientValues.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"Current value: {databaseValues.StartDate:d}");
                        }
                        if (databaseValues.InstructorID != clientValues.InstructorID)
                        {
                            Instructor databaseInstructor = await _context.Instructors.SingleOrDefaultAsync(i => i.ID == databaseValues.InstructorID);

                            ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor?.FullName}");
                        }

                        ModelState.AddModelError(string.Empty, "Error");
                        departmentToUpdate.RowVersion = (byte[])databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
コード例 #30
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Repository repository = new Repository();

            //get list of exercises from the database and prints it to the console
            List <Exercise> exercises = repository.GetExercises();

            repository.PrintExercises(exercises);

            Pause();

            // print exercises that use JS
            var JSExercises = exercises.Where(ex => ex.Language == "JavaScript").ToList();

            repository.PrintExercises(JSExercises);

            Pause();

            //add local instance of an exercise
            Exercise DoAllThings = new Exercise()
            {
                ExerciseName = "Do all the things", Language = "JavaScript"
            };

            //add that instance to the database
            repository.AddExerciseToDB(DoAllThings);

            exercises = repository.GetExercises();
            Console.Write("exercises after adding new");
            repository.PrintExercises(exercises);

            Pause();

            //get all instructors from database and print to console
            List <Instructor> instructors = repository.GetAllInstructorsWithCohorts();

            repository.PrintInstructors(instructors);

            Pause();

            //creating a new cohort, then a new instructor with that cohort included. adding to DB and printing to console
            Cohort Cohort32 = new Cohort()
            {
                Id = 3, CohortName = "Cohort 32"
            };
            Instructor instructor = new Instructor()
            {
                FirstName = "New", LastName = "Person", SlackHandle = "slackkk", Specialty = "none", Cohort = Cohort32
            };

            repository.AddInstructorToDB(instructor);
            instructors = repository.GetAllInstructorsWithCohorts();
            Console.Write("instructors after adding");
            repository.PrintInstructors(instructors);

            Pause();

            // get list of students from database and prints to console
            var students = repository.GetStudents();

            repository.PrintStudents(students);

            Pause();
        }
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }
            //READ departmentToUpdate.
            var departmentToUpdate = await _context.Departments.Include(i => i.Administrator).FirstOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                await TryUpdateModelAsync(deletedDepartment);

                //
                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes. The department was deleted by another user.");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            //View stores original RowVersion value in hidden filed. Method receivers that value in the param.
            //Before calling SaveChanges you must put original RowVersion property in the OriginalValues collection for entity.
            _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }

                catch (DbUpdateConcurrencyException ex)
                {
                    //Gets the affected Departmnt entity that have the updated values
                    //from the Entries property on the exception object.
                    var exceptionEntry = ex.Entries.Single();
                    //Collection has just one EntityEntry object. Use obj to get new values entered by
                    //the user and current database values.
                    var clientValues  = (Department)exceptionEntry.Entity;
                    var databaseEntry = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. The department was deleted by another user.");
                    }
                    //Adds custom error message for each column that has DB values different from what user entered on
                    //the Edit page.
                    else
                    {
                        var databaseValues = (Department)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", $"Current value: {databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValues.Budget)
                        {
                            ModelState.AddModelError("Budget", $"Current value: { databaseValues.Budget:c}");
                        }
                        if (databaseValues.StartDate != clientValues.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"Current value: { databaseValues.StartDate:d}");
                        }
                        if (databaseValues.InstructorID != clientValues.InstructorID)
                        {
                            Instructor databaseInstructor = await _context.Instructors.FirstOrDefaultAsync(i => i.ID == databaseValues.InstructorID);

                            ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor?.FullName}");
                        }

                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by another user after you got the original value. The "
                                                 + "edit operation was canceled and the current values in the database "
                                                 + "have been displayed. If you still want to edit this record, click "
                                                 + "the Save button again. Otherwise click the Back to List hyperlink.");
                        //Set RowVersion value of the departmentToUpdate to the new value retrieved from the database.
                        //The new RowVersion value will be stored in hidden field when edit page is redisplayed and next time user
                        //clicks Save, only concurrency errors that happen since the redisplay of the Edit page will be caught.
                        departmentToUpdate.RowVersion = (byte[])databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }

            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
コード例 #32
0
ファイル: ValuesController.cs プロジェクト: davidketner/Rent
        public ActionResult <string> Get()
        {
            //Service Testing //

            // Create Languages
            var l1 = new Language {
                Shortname = "CZ", Name = "Čeština"
            };
            var l2 = new Language {
                Shortname = "AJ", Name = "Angličtina"
            };
            var l3 = new Language {
                Shortname = "NJ", Name = "Němčina"
            };

            Svc.CreateLanguage(l1, userId);
            Svc.CreateLanguage(l2, userId);
            Svc.CreateLanguage(l3, userId);

            // Create LanguageLevels
            var ll1 = new LanguageLevel {
                Name = "A1", Level = 1
            };
            var ll2 = new LanguageLevel {
                Name = "A2", Level = 2
            };
            var ll3 = new LanguageLevel {
                Name = "B1", Level = 3
            };
            var ll4 = new LanguageLevel {
                Name = "B2", Level = 4
            };
            var ll5 = new LanguageLevel {
                Name = "C1", Level = 5
            };

            Svc.CreateLanguageLevel(ll1, userId);
            Svc.CreateLanguageLevel(ll2, userId);
            Svc.CreateLanguageLevel(ll3, userId);
            Svc.CreateLanguageLevel(ll4, userId);
            Svc.CreateLanguageLevel(ll5, userId);

            // Create Expertises
            var e1 = new Expertise {
                Name = "Snowbord", Shortname = "SNB"
            };
            var e2 = new Expertise {
                Name = "Lyžování", Shortname = "SKI"
            };

            Svc.CreateExpertise(e1, userId);
            Svc.CreateExpertise(e2, userId);

            // Create ExpertiseLevels
            var el1 = new ExpertiseLevel {
                Name = "Začátečník", Shortname = "ZA", Level = 1
            };
            var el2 = new ExpertiseLevel {
                Name = "Mírně pokročilý", Shortname = "MP", Level = 2
            };
            var el3 = new ExpertiseLevel {
                Name = "Pokročilý", Shortname = "PO", Level = 3
            };

            Svc.CreateExpertiseLevel(el1, userId);
            Svc.CreateExpertiseLevel(el2, userId);
            Svc.CreateExpertiseLevel(el3, userId);

            // Create WageRates
            var wr1 = new WageRate {
                Name = "Hodinová standart", Rate = 160, Percental = false
            };
            var wr2 = new WageRate {
                Name = "Procentuální standart", Rate = 10, Percental = true
            };

            Svc.CreateWageRate(wr1, userId);
            Svc.CreateWageRate(wr2, userId);
            //

            // Create Company
            var company = new Company {
                Name = "Ski Rychleby", UniqueIndex = 46
            };

            Svc.CreateCompany(company, userId);
            //

            // Create Rentals
            var r1 = new Rental {
                Name = "Travná", Shortname = "Travná", City = "Travná", Company = company, Country = "Česká republika"
            };
            var r2 = new Rental {
                Name = "Zálesí", Shortname = "Zálesí", City = "Zálesí", Company = company, Country = "Česká republika"
            };

            Svc.CreateRental(r1, userId);
            Svc.CreateRental(r2, userId);
            //

            // Create Tickets
            var t1 = new Ticket {
                Name = "Celosezónní", Rental = r1
            };
            var t2 = new Ticket {
                Name = "Dopolední", Rental = r1
            };
            var t3 = new Ticket {
                Name = "Celosezónní", Rental = r2
            };

            Svc.CreateTicket(t1, userId);
            Svc.CreateTicket(t2, userId);
            Svc.CreateTicket(t3, userId);
            //

            Svc.Commit();

            // Create Rental Places
            var rp1 = new RentalPlace {
                Name = "U sjezdovky", Description = "Místo pro sraz", RentalId = r1.Id
            };
            var rp2 = new RentalPlace {
                Name = "U vleku", RentalId = r1.Id
            };

            Svc.CreateRentalPlace(rp1, userId);
            Svc.CreateRentalPlace(rp2, userId);
            Svc.Commit();
            //

            // Create Instructor
            var i = new Instructor {
                Firstname = "David", Surname = "Tománek", Email = "*****@*****.**", MobilPhone = "777555111"
            };

            i.WageRates.Add(new InstructorWageRate {
                Default = true, WageRateId = wr1.Id
            });
            i.WageRates.Add(new InstructorWageRate {
                Default = false, WageRateId = wr2.Id
            });
            i.Expertises.Add(new InstructorExpertise {
                ExpertiseId = e2.Id, ExpertiseLevelId = el2.Id
            });
            i.Expertises.Add(new InstructorExpertise {
                ExpertiseId = e2.Id, ExpertiseLevelId = el3.Id
            });
            i.Rentals.Add(new InstructorRental {
                RentalId = r1.Id
            });
            i.Rentals.Add(new InstructorRental {
                RentalId = r2.Id
            });
            i.Tickets.Add(new InstructorTicket {
                TicketId = t1.Id, From = DateTime.Now, To = DateTime.Now.AddDays(50)
            });
            i.Tickets.Add(new InstructorTicket {
                TicketId = t3.Id, From = DateTime.Now, To = DateTime.Now.AddDays(50)
            });
            i.Languages.Add(new InstructorLanguage {
                LanguageId = l2.Id, LanguageLevelId = ll2.Id
            });
            i.Languages.Add(new InstructorLanguage {
                LanguageId = l3.Id, LanguageLevelId = ll1.Id
            });
            i.Languages.Add(new InstructorLanguage {
                LanguageId = l2.Id, LanguageLevelId = ll4.Id
            });
            i.Languages.Add(new InstructorLanguage {
                LanguageId = l2.Id, LanguageLevelId = ll5.Id
            });
            Svc.CreateInstructor(i, userId);
            Svc.Commit();
            //

            // Create Availabilities
            var a1 = new InstructorAvailability {
                InstructorId = i.Id, From = new DateTime(2018, 9, 6, 8, 0, 0), To = new DateTime(2018, 9, 9, 16, 30, 0)
            };
            var a2 = new InstructorAvailability {
                InstructorId = i.Id, From = new DateTime(2018, 9, 11, 10, 0, 0), To = new DateTime(2018, 9, 11, 16, 0, 0)
            };
            var avais = new List <InstructorAvailability>()
            {
                a1, a2
            };

            Svc.CreateInstructorAvailability(avais, userId);
            Svc.Commit();
            //

            // Create Courses
            var c1 = new Course {
                Name = "Ovesný - děti", From = new DateTime(2018, 9, 6, 8, 0, 0), To = new DateTime(2018, 9, 6, 10, 0, 0), ExpertiseId = e2.Id, ExpertiseLevelId = el2.Id, RentalId = r1.Id, LanguageId = l2.Id, RentalPlaceId = rp1.Id
            };
            var c2 = new Course {
                Name = "Toman - děti", From = new DateTime(2018, 9, 6, 9, 0, 0), To = new DateTime(2018, 9, 6, 11, 0, 0), ExpertiseId = e2.Id, ExpertiseLevelId = el2.Id, RentalId = r1.Id, LanguageId = l2.Id, RentalPlaceId = rp1.Id
            };
            var c3 = new Course {
                Name = "Dominik", From = new DateTime(2018, 9, 6, 10, 0, 0), To = new DateTime(2018, 9, 6, 11, 0, 0), ExpertiseId = e2.Id, ExpertiseLevelId = el2.Id, RentalId = r1.Id, LanguageId = l2.Id, RentalPlaceId = rp1.Id
            };
            var c4 = new Course {
                Name = "Lubos - děti", From = new DateTime(2018, 9, 5, 8, 0, 0), To = new DateTime(2018, 9, 5, 10, 0, 0), ExpertiseId = e2.Id, ExpertiseLevelId = el2.Id, RentalId = r1.Id, LanguageId = l2.Id, RentalPlaceId = rp1.Id
            };

            c1.Instructors.Add(new InstructorCourse {
                InstructorId = i.Id
            });
            c2.Instructors.Add(new InstructorCourse {
                InstructorId = i.Id
            });
            c3.Instructors.Add(new InstructorCourse {
                InstructorId = i.Id
            });
            c4.Instructors.Add(new InstructorCourse {
                InstructorId = i.Id
            });
            Svc.CreateCourse(c1, userId);
            Svc.Commit();
            Svc.CreateCourse(c2, userId);
            Svc.Commit();
            Svc.CreateCourse(c3, userId);
            Svc.Commit();
            Svc.CreateCourse(c4, userId);
            Svc.Commit();
            //

            // End Testing //
            return("[value1, value2]");
        }
コード例 #33
0
        public async Task <SignUpViewModel> Handle(SignUpCommand request, CancellationToken cancellationToken)
        {
            var duplicateUser = await _userManager.FindByEmailAsync(request.Email.EmailNormalize());

            if (duplicateUser != null)
            {
                if (duplicateUser.EmailConfirmed)
                {
                    throw new CustomException(new Error
                    {
                        Message   = _localizer["DuplicateUser"],
                        ErrorType = ErrorType.DuplicateUser
                    });
                }
                //if somebody signed up and close the app after
                duplicateUser.IsValidating = true;
                string code = ConfirmEmailCodeGenerator.GenerateCode();
                duplicateUser.ValidationCode = code;

                await _context.SaveChangesAsync(cancellationToken);

                _emailService.SendEmail(request.Email,
                                        "Farakhu", "EmailVerification", "EmailVerification",
                                        code);

                return(new SignUpViewModel());
            }
            switch (request.UserType)
            {
            case UserType.Instructor:
                var duplicateInstructor = _context.Instructors.
                                          FirstOrDefault(i => i.InstructorId == request.Id);
                if (duplicateInstructor != null)
                {
                    throw new CustomException(new Error
                    {
                        Message   = _localizer["DuplicateUser"],
                        ErrorType = ErrorType.DuplicateUser
                    });
                }
                break;

            case UserType.Student:
                var duplicateStudent = _context.Students.
                                       FirstOrDefault(s => s.StudentId == request.Id);
                if (duplicateStudent != null)
                {
                    throw new CustomException(new Error
                    {
                        Message   = _localizer["DuplicateUser"],
                        ErrorType = ErrorType.DuplicateUser
                    });
                }
                break;
            }

            BaseUser user = null;

            switch (request.UserType)
            {
            case UserType.Instructor:
                user = new Instructor
                {
                    Email        = request.Email.EmailNormalize(),
                    FirstName    = request.FirstName,
                    LastName     = request.LastName,
                    InstructorId = request.Id
                };
                break;

            case UserType.Student:
                user = new Student
                {
                    Email     = request.Email.EmailNormalize(),
                    FirstName = request.FirstName,
                    LastName  = request.LastName,
                    StudentId = request.Id
                };
                break;
            }

            var avatar = await _context.Files.FirstOrDefaultAsync(a => a.Id == "smiley.png", cancellationToken);

            user.AvatarId = avatar.Id;


            user.IsValidating = true;
            string validationCode = ConfirmEmailCodeGenerator.GenerateCode();

            user.ValidationCode = validationCode;

            var result = await _userManager.CreateAsync(user, request.Password);

            if (!result.Succeeded)
            {
                throw new CustomException(new Error
                {
                    Message   = _localizer["Unexpected"],
                    ErrorType = ErrorType.Unexpected
                });
            }

            await _userManager.AddToRoleAsync(user, request.UserType.ToString().Normalize());



            await _context.SaveChangesAsync(cancellationToken);

            _emailService.SendEmail(request.Email,
                                    "Farakhu", "EmailVerification", "EmailVerification",
                                    validationCode);

            return(new SignUpViewModel());
        }
コード例 #34
0
 public Disponibilidad NewItem(Instructor parent)
 {
     this.AddItem(Disponibilidad.NewChild(parent));
     return(this[Count - 1]);
 }
コード例 #35
0
ファイル: FileController.cs プロジェクト: 1000VIA/SRA
        public IHttpActionResult UploadFileInstructor()
        {
            try
            {
                //                List<LogResponseDTO> lstErrores = new List<LogResponseDTO>();
                var httpRequest = HttpContext.Current.Request;
                if (httpRequest.Files.Count > 0)
                {
                    var fileSavePath = string.Empty;

                    var docfiles = new List <string>();

                    var URLArchivo = "";

                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];
                        //  var filePath = HttpContext.Current.Server.MapPath("C:/UploadedFiles/");
                        var filePath = "C:/UploadedFiles/";

                        var GUID = Guid.NewGuid().ToString();

                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        fileSavePath = Path.Combine(filePath, GUID + "." + postedFile.FileName.Split('.')[1]);



                        postedFile.SaveAs(fileSavePath);

                        docfiles.Add(filePath);

                        // URLArchivo = "~/UploadedFiles/" + GUID + "." + postedFile.FileName.Split('.')[1];
                        URLArchivo = "C:/UploadedFiles/" + GUID + "." + postedFile.FileName.Split('.')[1];


                        string e = Path.GetExtension(URLArchivo);
                        if ((e != ".xlsx") && (e != ".xlsm"))
                        {
                            return(Ok(new { success = false, message = "La extencion del archivo no es válida" }));
                        }
                    }

                    string FilePath = URLArchivo.Split('/')[1];

                    // var reader = new StreamReader(File.OpenRead(HttpContext.Current.Server.MapPath("~/UploadedFiles/") + FilePath), Encoding.GetEncoding(1252));
                    //var reader = new StreamReader(File.OpenRead(("C:/UploadedFiles/") + FilePath), Encoding.GetEncoding(1252));


                    Instructor    oInstructor    = new Instructor();
                    VirtualidadBl oVirtualidadBL = new VirtualidadBl();

                    var book = new ExcelQueryFactory(URLArchivo);

                    var resultado = (from row in book.Worksheet("Hoja1")
                                     select row).ToList();

                    foreach (var values in resultado)
                    {
                        if (values[12] != "AREA")
                        {
                            var Inst = oVirtualidadBL.InstructorCedula(values[1]);

                            if (Inst == null)
                            {
                                oInstructor.Numero            = values[0];
                                oInstructor.Area              = values[12];
                                oInstructor.Cedula            = values[1];
                                oInstructor.Nombre            = values[2];
                                oInstructor.Apellido          = values[3];
                                oInstructor.Email             = values[4];
                                oInstructor.EmailAlternativo  = values[5];
                                oInstructor.MunicipioVivienda = values[6];
                                oInstructor.Telefono          = values[7];
                                oInstructor.Celular           = values[8];
                                oInstructor.DiaNacimiento     = values[9];
                                oInstructor.MesNacimiento     = values[10];
                                oInstructor.AnioNacimiento    = values[11];
                                oInstructor.Inicio_Contrato   = values[14];
                                oInstructor.Fin_Contrato      = values[15];
                                oInstructor.Profesion         = values[16];
                                oInstructor.ProgramaFormacion = values[17];
                                oInstructor.TipoContrato      = values[18];
                                oInstructor.Estado            = true;
                                oInstructor.EnvioCorreo       = false;
                                oInstructor.Num_Contrato      = "";
                                oInstructor.Adicion           = "";

                                oVirtualidadBL.GuardarInstructor(oInstructor);
                            }
                            else
                            {
                                return(Ok(new { success = false, message = "No se encontró archivo" }));
                            }
                        }
                    }

                    return(Ok(new { success = true, path = URLArchivo }));
                }
                else
                {
                    return(Ok(new { success = false, message = "No File" }));
                }
            }
            catch (Exception exc)
            {
                return(Ok(new { success = false, message = exc.Message }));
            }
        }
 public BoundaryTest()
 {
     _FitnessServices = new FitnessClubServices(service.Object);
     _appointment     = new Appointment
     {
         AppointmentId = 1,
         FullName      = "Kumar singh",
         CurrentWeight = 70,
         Height        = 172,
         Age           = 30,
         GoalWeight    = 60,
         Address       = "New Delhi",
         PhoneNumber   = 9631425152,
         Email         = "*****@*****.**",
         Remark        = "Want wet Loose"
     };
     _dietPlan = new DietPlan
     {
         DietplanId              = 1,
         Name                    = "Clean Eating",
         PlanOverview            = "Learn everything you need to know before starting the Clean Eating Diet plan including it's history, guidelines & components, & all of the science behind it.",
         Descriprtion            = "When we discuss diet plans we can typically put them along a spectrum where food quantity is on one end and food quality is on the other. Diets like If It Fits Your Macros(IIFYM) fall as far to the food quantity side as possible while clean eating falls as far to the food quality side as possible.<br> Additionally, in direct opposition to diets like IIFYM it imposes guidelines of what types of foods to eat and does not regulate calories of macros to any meaningful degree. The main principles of clean eating are centered around focusing on the quality of the foods you consume and ensuring they are “clean”. The principles can be summarized in one tenant: Choose whole, natural foods and seek to eliminate processed foods.",
         History                 = "As clean eating is not a well-defined dietary program it is difficult to trace the history of it as a dieting paradigm back to a singular beginning. One could give credit to the ancient Greek physician Hippocrates who penned one of the first works on dietary principles and is responsible for the famous quote, “Let food by the medicine and medicine be thy food”. <br>General Overview of Components & Main Principles of The Clean Eating Diet<br>Clean eating is based on the principle of eating whole, natural unprocessed foods. Most proponents of clean eating will suggest it is not truly a diet, but rather a view on what to eat and what not to eat. It focuses on food quality and not quantity, so calorie counting is not utilized in this dietary framework.",
         MealTimingFrequency     = "On principle, clean eating does not have strict requirements for meal timing or meal frequency (read: how many times a day you eat). <br>However, in application most clean eating programs suggest people eat 5 - 6 smaller, clean food, meals and snacks throughout the day rather than 3 main meals.",
         RestrictionsLimitations = "Clean eating places fairly substantial food restrictions on individuals. Clean eating diets require that people consume only whole, natural foods and eschew everything that is processed. This excludes pastas, breads, crackers, chips, cereals, and anything else that has been processed. This approach also excludes things like condiments (e.g. mustards and spreads) as well as dressings.<br> Additionally most beverages are restricted; this includes alcohol, soda, and juice.",
         Phases                  = "As traditionally thought of, the clean eating diet does not usually include phases.<br> Most prescriptions of the clean eating diet as instantiated in books, articles, and programs have people initiate the full spectrum of the diet at the outset. Some even include 30 day challenges in which whole, natural foods must be consumed for the entirety of the 30 days with no deviation from the protocol.",
         BestSuitedFor           = "Clean eating is best suited for people who are focused on the health properties of food, do not feel the desire to track the calories in their food, and who do not mind fairly restrictive approaches to nutrition. Clean eating allows substantial flexibility in the amount of food one eats, the timing and frequency, and with some effort and diligence the diet can be used for a wide range of people with drastically different goals (e.g. fat loss, muscle gain, or sport performance).",
         HowToFollow             = "How easy it is to follow the clean eating diet really depends on what type of person you are and your food preferences. For people who enjoy eating a wide variety of food, do not enjoy food restrictions, and would rather focus on the quantity of their food (i.e. the calories and macros) clean eating may be rather difficult to follow.<br> For people who are creatures of habit, do not mind eating within restricted dietary frameworks and do not enjoy counting their calories of macros clean eating can be an excellent dietary framework to follow.<br> Most people who practice clean eating long term usually build in small amounts of flexibility and follow either an 80/20 or 90/10 rule where they allow themselves to eat food on the restricted list 10-20% of the time.",
         Conclusion              = "Clean eating falls on the opposite end of the dietary spectrum from approaches like IIFYM or flexible dieting and focuses almost exclusively on food quality, not food quantity. The main principles of clean eating are centered around focusing on the quality of the foods you consume and ensuring they are “clean”.<br>The principles can be summarized in one tenant: Choose whole, natural foods and seek to eliminate processed foods.<br>The core principles of the diet can be listed as follows: avoid processed foods, avoid refined foods, avoid artificial ingredients, avoid alcohol, avoid soda and fruit juice.",
     };
     _instructor = new Instructor
     {
         InstructorId     = 1,
         Profession       = "Gym Owner",
         Competition      = "Ex-Bodybuilder",
         TopPlacing       = "2nd, British Championships",
         About            = "Doug started out as a physical trainer in the army. He was a competitive gymnast, diver and trampolinist. After leaving the army Doug worked as a personal trainer at his local gym. It was then Doug first started bodybuilding. After only 12 months on the bodybuilding scene Doug competed in the British championships where he placed a respectable 5th! In the following year Doug competed again to win 2nd place. Unfortunately Doug tore his rotator cuff and could no longer compete. He then became a national bodybuilding judge with the Natural Bodybuilders Association. Doug now runs a successful fitness centre where he trains males for bodybuilding and powerlifter competitions and females for physique and figure competitions. All of Doug's trainees have reached British championship level. Doug also provides sports specific training services and diet serivces for people from the UK, Europe and the US. Doug has 2 websites, Gemini Fitness Center & Pro Diets.",
         SuggestedWorkOut = "Doug's 4 Day Split Workout (extemely popular workout on M&S), The Super Toning Training Routine, 12 Week Beginners Routine, Maximum Strength Workout, Doug's Mega Cutting Routine."
     };
     _tools = new Tools
     {
         ToolsId     = 1,
         Name        = "Treadmill",
         Description = "It is one of the widely popular commercial gym equipment. This equipment offers a great warm up exercise before you indulge yourself in a hardcore, and more muscle and bone-stressing exercise machine. If you just want to shed off some weight and burn extra calories, this gym equipment will do the trick.",
     };
     _workout = new Workout
     {
         WorkoutId              = 1,
         Name                   = "Muscle Building",
         Descriprtion           = "A 12 week full body beginner workout routine designed to introduce you to a range of gym equipment and basic bodybuilding exercises in under 60 minutes.",
         MainGoal               = "Build Muscle",
         WorkoutType            = "Full Body",
         TrainingLevel          = "Beginner",
         ProgramDuration        = "12 Week",
         DaysPerWeek            = 3,
         TimePerWorkout         = "30-45 Minutes",
         EquipmentRequired      = "Barbell, Bodyweight, Cables, Dumbbells, Machines",
         TargetGender           = "Male & Female",
         RecommendedSupplements = "Whey Protein, Multivitamin, Fish Oil",
         Author                 = "Doug Lawrenson",
         WorkoutPDF             = ""
     };
 }
コード例 #37
0
        public static void Initialize(SchoolContext context)
        {
            // EnsureCreate method will automatically create the database
            // if it doesn't already exist.
            context.Database.EnsureCreated();

            // =================== students ====================
            // first, look for any students
            if (context.Students.Any())
            {
                // database has already been seeded (populated) with students
                return; // exits
            }

            // if we're here, students do not already exist - need to seed (populate)
            var students = new Student[]
            {
                new Student
                {
                    FirstName      = "Carson",
                    LastName       = "Alexander",
                    Email          = "*****@*****.**",
                    EnrollmentDate = DateTime.Parse("2017-09-01"),
                    Address        = "4 Flanders Court",
                    City           = "Moncton",
                    Province       = "NB",
                    PostalCode     = "E1C 0K6"
                },
                new Student
                {
                    FirstName      = "Meridith",
                    LastName       = "Alonso",
                    Email          = "*****@*****.**",
                    EnrollmentDate = DateTime.Parse("2017-09-01"),
                    Address        = "205 Argyle Street",
                    City           = "Moncton",
                    Province       = "NB",
                    PostalCode     = "E1C 8V2"
                }
            }; // end students array

            // loop the students array and add each student to database context
            foreach (Student s in students)
            {
                context.Students.Add(s);
            }

            // save the context
            context.SaveChanges();


            // =================== instructors ====================
            // now for the instructors
            var instructors = new Instructor[]
            {
                new Instructor
                {
                    FirstName  = "Brett",
                    LastName   = "Dinelli",
                    Email      = "*****@*****.**",
                    HireDate   = DateTime.Parse("1996-01-31"),
                    Address    = "778 Centrale",
                    City       = "Dieppe",
                    Province   = "NB",
                    PostalCode = "E1A 5Z5"
                },
                new Instructor
                {
                    FirstName  = "Frank",
                    LastName   = "Bekkering",
                    Email      = "*****@*****.**",
                    HireDate   = DateTime.Parse("1996-01-31"),
                    Address    = "456 Main Street",
                    City       = "Moncton",
                    Province   = "NB",
                    PostalCode = "E1A 5Z5"
                }
            }; // end instructors array

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

            // save it
            context.SaveChanges();

            // ================== courses ==================
            var courses = new Course[]
            {
                new Course
                {
                    CourseID = 1050,
                    Title    = "Chemistry",
                    Credits  = 3
                },
                new Course
                {
                    CourseID = 4022,
                    Title    = "MicroEconomics",
                    Credits  = 3
                }
            };

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

            context.SaveChanges();

            // ================== enrollments ==================
            var enrollments = new Enrollment[]
            {
                new Enrollment
                {
                    CourseID  = 1050,
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    Grade     = Grade.A
                },
                new Enrollment
                {
                    CourseID  = 4022,
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    Grade     = Grade.B
                }
            };

            foreach (Enrollment e in enrollments)
            {
                context.Enrollments.Add(e);
            }

            context.SaveChanges();
        } // end Initialize method
コード例 #38
0
        public async Task <IActionResult> Get()
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT c.Id AS CohortId, c.CohortName, s.Id AS StudentId, 
                                        s.FirstName AS SFirstName, s.LastName AS SLastName,
                                        s.SlackHandle AS SSlackHandle, s.CohortId, e.Id AS ExerciseId, 
                                        e.ExerciseName, e.ExerciseLanguage,
                                        i.Id AS InstructorId, i.FirstName AS IFirstName, 
                                        i.LastName AS ILastName, i.SlackHandle AS ISlackHandle, 
                                        i.CohortId FROM Cohort c
                                        INNER JOIN Student s ON c.Id = s.CohortId
                                        LEFT JOIN StudentExercise se ON s.Id = se.StudentId
                                        LEFT JOIN Exercise e ON e.Id = se.ExerciseId
                                        LEFT JOIN Instructor i ON c.Id = i.CohortId";
                    SqlDataReader reader = await cmd.ExecuteReaderAsync();

                    List <Cohort> cohorts = new List <Cohort>();

                    while (reader.Read())
                    {
                        var cohortId       = reader.GetInt32(reader.GetOrdinal("CohortId"));
                        var alreadyCohort  = cohorts.FirstOrDefault(c => c.Id == cohortId);
                        var hasStudents    = !reader.IsDBNull(reader.GetOrdinal("StudentId"));
                        var hasInstructors = !reader.IsDBNull(reader.GetOrdinal("InstructorId"));


                        if (alreadyCohort == null)
                        {
                            Cohort cohort = new Cohort
                            {
                                Id          = cohortId,
                                CohortName  = reader.GetString(reader.GetOrdinal("CohortName")),
                                Students    = new List <Student>(),
                                Instructors = new List <Instructor>()
                            };

                            cohorts.Add(cohort);

                            if (hasStudents)
                            {
                                Student student = new Student()
                                {
                                    Id          = reader.GetInt32(reader.GetOrdinal("StudentId")),
                                    FirstName   = reader.GetString(reader.GetOrdinal("SFirstName")),
                                    LastName    = reader.GetString(reader.GetOrdinal("SLastName")),
                                    SlackHandle = reader.GetString(reader.GetOrdinal("SSlackHandle")),
                                    Exercise    = new List <Exercise>(),
                                    Cohort      = new Cohort()
                                    {
                                        Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                        CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                    }
                                };


                                if (!cohort.Students.Contains(student))
                                {
                                    cohort.Students.Add(student);
                                }
                                ;


                                if (hasInstructors)
                                {
                                    Instructor instructor = new Instructor()
                                    {
                                        Id          = reader.GetInt32(reader.GetOrdinal("InstructorId")),
                                        FirstName   = reader.GetString(reader.GetOrdinal("IFirstName")),
                                        LastName    = reader.GetString(reader.GetOrdinal("ILastName")),
                                        SlackHandle = reader.GetString(reader.GetOrdinal("ISlackHandle")),
                                        Cohort      = new Cohort()
                                        {
                                            Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                            CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                        }
                                    };


                                    if (!cohort.Instructors.Contains(instructor))
                                    {
                                        cohort.Instructors.Add(instructor);
                                    }
                                }
                            }


                            else
                            {
                                if (hasStudents)
                                {
                                    Student student = new Student()

                                    {
                                        Id          = reader.GetInt32(reader.GetOrdinal("StudentId")),
                                        FirstName   = reader.GetString(reader.GetOrdinal("SFirstName")),
                                        LastName    = reader.GetString(reader.GetOrdinal("SLastName")),
                                        SlackHandle = reader.GetString(reader.GetOrdinal("SSlackHandle")),
                                        CohortId    = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                        Exercise
                                               = new List <Exercise>(),
                                        Cohort = new Cohort()
                                        {
                                            Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                            CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                        }
                                    };


                                    if (!alreadyCohort.Students.Exists(s => s.Id == student.Id))
                                    {
                                        alreadyCohort.Students.Add(student);
                                    }
                                }

                                if (hasInstructors)
                                {
                                    Instructor instructor = new Instructor()
                                    {
                                        Id          = reader.GetInt32(reader.GetOrdinal("InstructorId")),
                                        FirstName   = reader.GetString(reader.GetOrdinal("IFirstName")),
                                        LastName    = reader.GetString(reader.GetOrdinal("ILastName")),
                                        SlackHandle = reader.GetString(reader.GetOrdinal("ISlackHandle")),
                                        CohortId    = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                        Cohort      = new Cohort()
                                        {
                                            Id         = reader.GetInt32(reader.GetOrdinal("CohortId")),
                                            CohortName = reader.GetString(reader.GetOrdinal("CohortName"))
                                        }
                                    };

                                    if (!alreadyCohort.Instructors.Exists(i => i.Id == instructor.Id))
                                    {
                                        alreadyCohort.Instructors.Add(instructor);
                                    }
                                }
                            }
                        }
                    }


                    reader.Close();

                    return(Ok(cohorts));
                }
            }
        }
コード例 #39
0
        public async Task OnGetAsync(int?id, int?CourseID)
        {
            //Instructor = await _context.Instructors.ToListAsync();
            InstructorData             = new InstructorIndexData();
            InstructorData.Instructors = await _context.Instructors
                                         .Include(i => i.OfficeAssignment)
                                         .Include(i => i.CourseAssignments)
                                         .ThenInclude(i => i.Course)
                                         .ThenInclude(i => i.Department)

                                         /*
                                          * This was added for eager loading, however, if the user barely need to look at enrolment, we could delegate the query until user selects it
                                          */
                                         //.Include(i => i.CourseAssignments)
                                         //    .ThenInclude(i => i.Course)
                                         //    .ThenInclude(i => i.Enrollments)
                                         //    .ThenInclude(i => i.Student)
                                         //.AsNoTracking()
                                         .OrderBy(i => i.LastName)
                                         .ToListAsync();

            /*
             * The filters will return a collection of a single item
             * .Single() converts that to a single Instructor/Course entity
             * - will complain if the collection is empty though
             * .SingleOrDefault() will return null if the collection is empty
             */

            if (id != null)
            {
                InstructorID = id.Value;

                /*
                 * .Where(cond).Single() or .Single(cond) are equivalent
                 */
                //Instructor instructor = InstructorData.Instructors.Where(i => i.ID == id.Value).Single();
                Instructor instructor = InstructorData.Instructors.Single(i => i.ID == id.Value);

                InstructorData.Courses = instructor.CourseAssignments.Select(s => s.Course);
            }

            if (CourseID != null)
            {
                this.CourseID = CourseID.Value;
                var selectedCourse = InstructorData.Courses
                                     .Where(s => s.CourseID == CourseID.Value)
                                     .Single();

                /*
                 * Added this to only load enrolment details when clicked
                 */
                await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync();

                foreach (Enrollment en in selectedCourse.Enrollments)
                {
                    await _context.Entry(en).Reference(x => x.Student).LoadAsync();
                }

                InstructorData.Enrollments = selectedCourse.Enrollments;
            }
        }
コード例 #40
0
 public InstructorSystem(Instructor std)
 {
     this.instructor = std;
 }
コード例 #41
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var departmentToUpdate = await _context.Departments.Include(i => i.Administrator).SingleOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty,
                                         "We can't save the department. It looks like it's already been deleted by another user.");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "We can't save the department. It looks like it's already been deleted by another user.");
                    }
                    else
                    {
                        var databaseValues = (Department)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", $"Current value: {databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValues.Budget)
                        {
                            ModelState.AddModelError("Budget", $"Current value: {databaseValues.Budget:c}");
                        }
                        if (databaseValues.StartDate != clientValues.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"Current value: {databaseValues.StartDate:d}");
                        }
                        if (databaseValues.InstructorID != clientValues.InstructorID)
                        {
                            Instructor databaseInstructor = await _context.Instructors.SingleAsync(i => i.ID == databaseValues.InstructorID);

                            ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor.FullName}");
                        }

                        ModelState.AddModelError(string.Empty, "The department has just been edited by "
                                                 + "somebody else. If you still want to edit this department, press "
                                                 + "the Save button again. Otherwise press the Back to List hyperlink.");
                        departmentToUpdate.RowVersion = (byte[])databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
コード例 #42
0
        /// <summary>
        /// Asigna los datos de origen para controles que dependen de otros
        /// </summary>
        /// <param name="controlName"></param>
        protected override void SetDependentControlSource(string controlName)
        {
            try
            {
                switch (controlName)
                {
                case "Fecha_DTP":
                {
                    PgMng.Reset(6, 1, Face.Resources.Messages.REFRESHING_DATA, this);

                    if (_entity != null && (Fecha_DTP.Value != _day ||
                                            (_disponibilidad != null && _disponibilidad.OidInstructor != _entity.Oid)))
                    {
                        _day = Fecha_DTP.Value;
                        while (_day.DayOfWeek != System.DayOfWeek.Monday)
                        {
                            _day = _day.AddDays(-1);
                        }

                        FFIn_Label.Text    = "A Sábado, " + _day.AddDays(5).ToShortDateString();
                        FInicio_Label.Text = "De Lunes, " + _day.ToShortDateString();

                        if (_day < Fecha_DTP.MinDate)
                        {
                            Fecha_DTP.Value = Fecha_DTP.MinDate;
                        }
                        else
                        {
                            Fecha_DTP.Value = _day;
                        }

                        PgMng.Grow();

                        if (_disponibilidad != null && _disponibilidad.IsDirty)
                        {
                            /*foreach (Disponibilidad item in _entity.Disponibilidades)
                             * {
                             *  if (item.Oid == _disponibilidad.Oid)
                             *  {
                             *      int index = _entity.Disponibilidades.IndexOf(item);
                             *      _disponibilidad.ClasesSemanales = Convert.ToInt64(Clases_TB.Text);
                             *      //_entity.Disponibilidades[index] = _disponibilidad;
                             *      break;
                             *  }
                             * }*/
                            _disponibilidad.ClasesSemanales = Convert.ToInt64(Clases_TB.Text);
                            _disponibilidad.Observaciones   = Observaciones_TB.Text;
                        }

                        PgMng.Grow();

                        if (_entity.Disponibilidades != null)
                        {
                            Disponibilidad disp = null;

                            foreach (Disponibilidad item in _entity.Disponibilidades)
                            {
                                if (item.FechaInicio.Date.Equals(_day.Date))
                                {
                                    disp = item;
                                    break;
                                }
                            }

                            PgMng.Grow();

                            Datos_Disponibilidad.DataSource = _entity.Disponibilidades;
                            if (disp == null)         // hay que crear la nueva disponibilidad
                            {
                                _disponibilidad             = _entity.Disponibilidades.NewItem(_entity);
                                _disponibilidad.FechaInicio = _day;
                                _disponibilidad.FechaFin    = _day.AddDays(4);
                                PgMng.Grow();

                                LoadDefaultAction();
                                Observaciones_TB.Text = string.Empty;
                                PgMng.Grow();
                            }
                            else
                            {        //hay que editar la que existe
                                _disponibilidad = disp;

                                Fecha_DTP.Value    = _disponibilidad.FechaInicio;
                                FFIn_Label.Text    = "A Sábado, " + _disponibilidad.FechaFin.ToShortDateString();
                                FInicio_Label.Text = "De Lunes, " + _disponibilidad.FechaInicio.ToShortDateString();
                                PgMng.Grow();

                                L8AM_CB.Checked       = _disponibilidad.L8AM;
                                M8AM_CB.Checked       = _disponibilidad.M8AM;
                                X8AM_CB.Checked       = _disponibilidad.X8AM;
                                J8AM_CB.Checked       = _disponibilidad.J8AM;
                                V8AM_CB.Checked       = _disponibilidad.V8AM;
                                L1_CB.Checked         = _disponibilidad.L1;
                                L2_CB.Checked         = _disponibilidad.L2;
                                L3_CB.Checked         = _disponibilidad.L3;
                                L4_CB.Checked         = _disponibilidad.L4;
                                L5_CB.Checked         = _disponibilidad.L5;
                                L6_CB.Checked         = _disponibilidad.L6;
                                L7_CB.Checked         = _disponibilidad.L7;
                                L8_CB.Checked         = _disponibilidad.L8;
                                L9_CB.Checked         = _disponibilidad.L9;
                                L10_CB.Checked        = _disponibilidad.L10;
                                L11_CB.Checked        = _disponibilidad.L11;
                                L12_CB.Checked        = _disponibilidad.L12;
                                M1_CB.Checked         = _disponibilidad.M1;
                                M2_CB.Checked         = _disponibilidad.M2;
                                M3_CB.Checked         = _disponibilidad.M3;
                                M4_CB.Checked         = _disponibilidad.M4;
                                M5_CB.Checked         = _disponibilidad.M5;
                                M6_CB.Checked         = _disponibilidad.M6;
                                M7_CB.Checked         = _disponibilidad.M7;
                                M8_CB.Checked         = _disponibilidad.M8;
                                M9_CB.Checked         = _disponibilidad.M9;
                                M10_CB.Checked        = _disponibilidad.M10;
                                M11_CB.Checked        = _disponibilidad.M11;
                                M12_CB.Checked        = _disponibilidad.M12;
                                X1_CB.Checked         = _disponibilidad.X1;
                                X2_CB.Checked         = _disponibilidad.X2;
                                X3_CB.Checked         = _disponibilidad.X3;
                                X4_CB.Checked         = _disponibilidad.X4;
                                X5_CB.Checked         = _disponibilidad.X5;
                                X6_CB.Checked         = _disponibilidad.X6;
                                X7_CB.Checked         = _disponibilidad.X7;
                                X8_CB.Checked         = _disponibilidad.X8;
                                X9_CB.Checked         = _disponibilidad.X9;
                                X10_CB.Checked        = _disponibilidad.X10;
                                X11_CB.Checked        = _disponibilidad.X11;
                                X12_CB.Checked        = _disponibilidad.X12;
                                J1_CB.Checked         = _disponibilidad.J1;
                                J2_CB.Checked         = _disponibilidad.J2;
                                J3_CB.Checked         = _disponibilidad.J3;
                                J4_CB.Checked         = _disponibilidad.J4;
                                J5_CB.Checked         = _disponibilidad.J5;
                                J6_CB.Checked         = _disponibilidad.J6;
                                J7_CB.Checked         = _disponibilidad.J7;
                                J8_CB.Checked         = _disponibilidad.J8;
                                J9_CB.Checked         = _disponibilidad.J9;
                                J10_CB.Checked        = _disponibilidad.J10;
                                J11_CB.Checked        = _disponibilidad.J11;
                                J12_CB.Checked        = _disponibilidad.J12;
                                V1_CB.Checked         = _disponibilidad.V1;
                                V2_CB.Checked         = _disponibilidad.V2;
                                V3_CB.Checked         = _disponibilidad.V3;
                                V4_CB.Checked         = _disponibilidad.V4;
                                V5_CB.Checked         = _disponibilidad.V5;
                                V6_CB.Checked         = _disponibilidad.V6;
                                V7_CB.Checked         = _disponibilidad.V7;
                                V8_CB.Checked         = _disponibilidad.V8;
                                V9_CB.Checked         = _disponibilidad.V9;
                                V10_CB.Checked        = _disponibilidad.V10;
                                V11_CB.Checked        = _disponibilidad.V11;
                                V12_CB.Checked        = _disponibilidad.V12;
                                S1_CB.Checked         = _disponibilidad.S1;
                                S2_CB.Checked         = _disponibilidad.S2;
                                S3_CB.Checked         = _disponibilidad.S3;
                                S4_CB.Checked         = _disponibilidad.S4;
                                S0_CB.Checked         = _disponibilidad.S0;
                                L0_CB.Checked         = _disponibilidad.L0;
                                M0_CB.Checked         = _disponibilidad.M0;
                                X0_CB.Checked         = _disponibilidad.X0;
                                J0_CB.Checked         = _disponibilidad.J0;
                                V0_CB.Checked         = _disponibilidad.V0;
                                ND_L_CB.Checked       = _disponibilidad.NdL;
                                ND_M_CB.Checked       = _disponibilidad.NdM;
                                ND_X_CB.Checked       = _disponibilidad.NdX;
                                ND_J_CB.Checked       = _disponibilidad.NdJ;
                                ND_V_CB.Checked       = _disponibilidad.NdV;
                                ND_S_CB.Checked       = _disponibilidad.NdS;
                                Clases_TB.Text        = _disponibilidad.ClasesSemanales.ToString();
                                Observaciones_TB.Text = _disponibilidad.Observaciones.ToString();
                                PgMng.Grow();
                            }
                        }
                    }

                    FormatDefaultButtons();
                } break;

                case "Instructores_CB":
                {
                    PgMng.Reset(3, 1, Face.Resources.Messages.REFRESHING_DATA, this);

                    if (_entity != null && !(this is DisponibilidadEditForm))
                    {
                        if (_entity.IsDirty)
                        {
                            SaveObject();
                        }
                        _entity.CloseSession();
                    }
                    PgMng.Grow();
                    if (Instructores_CB.SelectedItem != null && ((ComboBoxSource)Instructores_CB.SelectedItem).Oid != 0)
                    {
                        if (_entity != null)
                        {
                            if (_entity.Oid != ((ComboBoxSource)Instructores_CB.SelectedItem).Oid)
                            {
                                if (this is DisponibilidadEditForm)
                                {
                                    if (_entity.IsDirty)
                                    {
                                        SaveObject();
                                    }
                                    _entity.CloseSession();
                                }
                                _entity = Instructor.Get(((ComboBoxSource)Instructores_CB.SelectedItem).Oid, false);
                                _entity.LoadChilds(typeof(Disponibilidad), false, false);
                                _entity.BeginEdit();
                                Datos_Disponibilidad.DataSource = _entity.Disponibilidades;
                            }
                        }
                        else
                        {
                            _entity = Instructor.Get(((ComboBoxSource)Instructores_CB.SelectedItem).Oid, false, _session_code);
                            _entity.LoadChilds(typeof(Disponibilidad), false, false);
                            _entity.BeginEdit();
                            Datos_Disponibilidad.DataSource = _entity.Disponibilidades;
                        }

                        Fecha_DTP.Value = DateTime.Today;

                        _default = _entity.GetPredeterminado();
                        SetDependentControlSource(Fecha_DTP.Name);
                    }
                } break;

                case "Clases_TB":
                {
                    PgMng.Reset(1, 1, Face.Resources.Messages.REFRESHING_DATA, this);
                    if (_disponibilidad != null)
                    {
                        try
                        {
                            _disponibilidad.ClasesSemanales = Convert.ToInt64(Clases_TB.Text);
                        }
                        catch
                        {
                            _disponibilidad.ClasesSemanales = 15;
                        }
                    }
                } break;
                }
            }
            finally
            {
                PgMng.FillUp();
            }
        }
コード例 #43
0
        public ActionResult Detalles(int id)
        {
            Instructor busqueda = db.Instructor.Find(id);

            return(View(busqueda));
        }
コード例 #44
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var departmentToUpdate = await _context.Departments.Include(i => i.Administrator).SingleOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes. The department was deleted by another user.");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", deletedDepartment.InstructorID);
                return(View(deletedDepartment));
            }

            _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. The department was deleted by another user.");
                    }
                    else
                    {
                        var databaseValues = (Department)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", $"Current value: {databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValues.Budget)
                        {
                            ModelState.AddModelError("Budget", $"Current value: {databaseValues.Budget:c}");
                        }
                        if (databaseValues.StartDate != clientValues.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"Current value: {databaseValues.StartDate:d}");
                        }
                        if (databaseValues.InstructorID != clientValues.InstructorID)
                        {
                            Instructor databaseInstructor = await _context.Instructors.SingleOrDefaultAsync(i => i.ID == databaseValues.InstructorID);

                            ModelState.AddModelError("InstructorID", $"Current value: {databaseInstructor?.FullName}");
                        }

                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by anothe ruser after you got the orginal value. The "
                                                 + "edit operation was cancelled and the current values in the database "
                                                 + "have been displayed. If you still want to edit this record, click "
                                                 + "the Save button again. Otherwise click the Back to List hyperlink.");
                        departmentToUpdate.RowVersion = (byte[])databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(View(departmentToUpdate));
        }
コード例 #45
0
        public ActionResult Eliminar(int id)
        {
            Instructor busqueda = db.Instructor.Find(id);

            return(View(busqueda));
        }
コード例 #46
0
        public async Task <PartialViewResult> UpdateInstructor(int instructorID)
        {
            Instructor model = await db_context.Instructors.AsNoTracking().SingleAsync(x => x.UserID == instructorID);

            return(PartialView(model));
        }
コード例 #47
0
        // GET: Cohorts/Delete/5
        public ActionResult Delete(int id)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                                        SELECT s.Id AS StudentId, s.FirstName AS StudentFirstName, 
                                        s.LastName AS StudentLastName, s.SlackHandle AS StudentSlackHandle,
                                        i.Id AS InstructorId, i.FirstName AS InstructorFirstName, 
                                        i.LastName AS InstructorLastName, i.SlackHandle AS InstructorSlackHandle,
                                        c.Id AS CohortId, c.Name AS CohortName
                                        FROM Students s
                                        FULL OUTER JOIN Instructors i ON s.CohortId = i.CohortId
                                        LEFT JOIN Cohorts c ON c.Id = s.CohortId OR c.Id = i.CohortId
                                        WHERE s.CohortId = @id OR i.CohortId = @id
                                        ";
                    cmd.Parameters.Add(new SqlParameter("@id", id));
                    SqlDataReader reader = cmd.ExecuteReader();

                    Cohort cohort = null;

                    if (reader.Read())
                    {
                        cohort = new Cohort()
                        {
                            Id = reader.GetInt32(reader.GetOrdinal("CohortId")),
                            Name = reader.GetString(reader.GetOrdinal("CohortName"))
                        };
                        if (!reader.IsDBNull(reader.GetOrdinal("StudentId")))
                        {
                            Student student = new Student()
                            {
                                Id = reader.GetInt32(reader.GetOrdinal("StudentId")),
                                FirstName = reader.GetString(reader.GetOrdinal("StudentFirstName")),
                                LastName = reader.GetString(reader.GetOrdinal("StudentLastName")),
                                SlackHandle = reader.GetString(reader.GetOrdinal("StudentSlackHandle")),
                                CohortId = reader.GetInt32(reader.GetOrdinal("CohortId"))
                            };
                            cohort.StudentList.Add(student);
                        }
                        if (!reader.IsDBNull(reader.GetOrdinal("InstructorId")))
                        {
                            Instructor instructor = new Instructor()
                            {
                                Id = reader.GetInt32(reader.GetOrdinal("InstructorId")),
                                FirstName = reader.GetString(reader.GetOrdinal("InstructorFirstName")),
                                LastName = reader.GetString(reader.GetOrdinal("InstructorLastName")),
                                SlackHandle = reader.GetString(reader.GetOrdinal("InstructorSlackHandle")),
                                CohortId = reader.GetInt32(reader.GetOrdinal("CohortId"))
                            };
                            cohort.InstructorList.Add(instructor);
                        }
                        reader.Close();
                    }
                    else
                    {
                        cohort = GetCohortById(id);
                    }
                    return View(cohort);
                }
            }
        }
コード例 #48
0
        public static void Initialize(SchoolContext context)
        {
            //context.Database.EnsureCreated();     //Remove EnsureCreated by comment

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                    s.Student.ID == e.StudentID &&
                    s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
コード例 #49
0
ファイル: TPT.Designer.cs プロジェクト: zealoussnow/OneCode
 /// <summary>
 /// Create a new Instructor object.
 /// </summary>
 /// <param name="personID">Initial value of PersonID.</param>
 public static Instructor CreateInstructor(int personID)
 {
     Instructor instructor = new Instructor();
     instructor.PersonID = personID;
     return instructor;
 }
コード例 #50
0
 public InstructorEditViewModel(int id)
 {
     instructor = InstructorRepository.GetInstructor(id);
     CohortSelectFactory();
 }
コード例 #51
0
ファイル: Student.cs プロジェクト: SamDelBrocco/IT-1050
 public Student(string name, Instructor teacher)
 {
     this.Name = name;
     this.Teacher = teacher;
 }
コード例 #52
0
        public ActionResult Delete(int id)
        {
            try
            {
                try
                {
                    string ConnectionString = "Server = localhost; Port = 3306; Database = contosouniversity; Uid = root; Pwd = 1234";

                    Instructor      instructor = new Instructor();
                    MySqlDataReader read;
                    using (MySqlConnection conn = new MySqlConnection(ConnectionString))
                    {
                        conn.Open();

                        using (MySqlCommand cmd = new MySqlCommand("DeleteInstructor", conn))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;

                            cmd.Parameters.AddWithValue("@_Id", id);

                            read = cmd.ExecuteReader();


                            while (read.Read())
                            {
                                instructor.LastName     = read["LastName"].ToString();
                                instructor.FirstMidName = read["FirstMidName"].ToString();
                                instructor.HireDate     = Convert.ToDateTime(read["HireDate"]);
                            }
                            if (read == null)
                            {
                                return(HttpNotFound());
                            }
                        }

                        conn.Close();
                    }
                }//End try
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors: ",
                                          eve.Entry.Entity.GetType().Name, eve.Entry.State);

                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                              ve.PropertyName, ve.ErrorMessage);
                        } //End secod foreach
                    }     //End firts foreach
                    throw;
                }         //End Catch

                return(RedirectToAction("Index"));
            }//End try
            catch (Exception e)
            {
                Console.WriteLine(e);

                return(View());
            } //End Catch
        }     //End Method
コード例 #53
0
        static void Main(string[] args)
        {
            Gimnasio gim = new Gimnasio();
            Alumno   a1  = new Alumno(1, "Juan", "Lopez", "12234456", EntidadesAbstractas.Persona.ENacionalidad.Argentino, Gimnasio.EClases.CrossFit, Alumno.EEstadoCuenta.MesPrueba);

            gim += a1;
            try
            {
                Alumno a2 = new Alumno(2, "Juana", "Martinez", "12234458", EntidadesAbstractas.Persona.ENacionalidad.Extranjero, Gimnasio.EClases.Natacion, Alumno.EEstadoCuenta.Deudor);
                gim += a2;
            }
            catch (NacionalidadInvalidaException e)
            {
                Console.WriteLine(e.Message);
            }
            try
            {
                Alumno a3 = new Alumno(3, "José", "Gutierrez", "12234456", EntidadesAbstractas.Persona.ENacionalidad.Argentino, Gimnasio.EClases.CrossFit, Alumno.EEstadoCuenta.MesPrueba);
                gim += a3;
            }
            catch (AlumnoRepetidoException e)
            {
                Console.WriteLine(e.Message);
            }
            Alumno a4 = new Alumno(4, "Miguel", "Hernandez", "92264456", EntidadesAbstractas.Persona.ENacionalidad.Extranjero, Gimnasio.EClases.Pilates, Alumno.EEstadoCuenta.AlDia);

            gim += a4;
            Alumno a5 = new Alumno(5, "Carlos", "Gonzalez", "12236456", EntidadesAbstractas.Persona.ENacionalidad.Argentino, Gimnasio.EClases.CrossFit, Alumno.EEstadoCuenta.AlDia);

            gim += a5;
            Alumno a6 = new Alumno(6, "Juan", "Perez", "12234656", EntidadesAbstractas.Persona.ENacionalidad.Argentino, Gimnasio.EClases.Natacion, Alumno.EEstadoCuenta.Deudor);

            gim += a6;
            Alumno a7 = new Alumno(7, "Joaquin", "Suarez", "91122456", EntidadesAbstractas.Persona.ENacionalidad.Extranjero, Gimnasio.EClases.Natacion, Alumno.EEstadoCuenta.AlDia);

            gim += a7;
            Alumno a8 = new Alumno(8, "Rodrigo", "Smith", "22236456", EntidadesAbstractas.Persona.ENacionalidad.Argentino, Gimnasio.EClases.Pilates, Alumno.EEstadoCuenta.AlDia);

            gim += a8;

            Instructor i1 = new Instructor(1, "Juan", "Lopez", "12234456", EntidadesAbstractas.Persona.ENacionalidad.Argentino);

            gim += i1;
            Instructor i2 = new Instructor(2, "Roberto", "Juarez", "32234456", EntidadesAbstractas.Persona.ENacionalidad.Argentino);

            gim += i2;

            try
            {
                gim += Gimnasio.EClases.CrossFit;
            }
            catch (SinInstructorException e)
            {
                Console.WriteLine(e.Message);
            }
            try
            {
                gim += Gimnasio.EClases.Natacion;
            }
            catch (SinInstructorException e)
            {
                Console.WriteLine(e.Message);
            }
            try
            {
                gim += Gimnasio.EClases.Pilates;
            }
            catch (SinInstructorException e)
            {
                Console.WriteLine(e.Message);
            }
            try
            {
                gim += Gimnasio.EClases.Yoga;
            }
            catch (SinInstructorException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine(gim.ToString());

            Console.ReadKey();

            try
            {
                Gimnasio.Guardar(gim);
                Console.WriteLine("Archivo de Gimnasio guardado");
            }
            catch (ArchivosException e)
            {
                Console.WriteLine(e.Message);
            }
            try
            {
                int jornada = 0;
                Jornada.Guardar(gim[jornada]);
                Console.WriteLine("Archivo de Jornada {0} guardado", jornada);
            }
            catch (ArchivosException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
コード例 #54
0
        public void UpdateInstructorCourses(SchoolContext context, string[] selectedCourses, Instructor instructorToUpdate)
        {
            if (selectedCourses == null)
            {
                instructorToUpdate.CourseAssignments = new List <CourseAssignment>();
                return;
            }

            var selectedCoursesHS = new HashSet <string>(selectedCourses);
            var instructorCourses = new HashSet <int>
                                        (instructorToUpdate.CourseAssignments.Select(c => c.Course.CourseID));

            foreach (var course in context.Course)
            {
                if (selectedCoursesHS.Contains(course.CourseID.ToString()))
                {
                    if (!instructorCourses.Contains(course.CourseID))
                    {
                        instructorToUpdate.CourseAssignments.Add(
                            new CourseAssignment
                        {
                            InstructorID = instructorToUpdate.ID,
                            CourseID     = course.CourseID
                        });
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.CourseID))
                    {
                        CourseAssignment courseToRemove
                            = instructorToUpdate
                              .CourseAssignments
                              .SingleOrDefault(i => i.CourseID == course.CourseID);
                        context.Remove(courseToRemove);
                    }
                }
            }
        }
コード例 #55
0
ファイル: Teacher.cs プロジェクト: sasa333/course-fantastic
		public InstructorAssignment CreateAssignment(Instructor teacher, SubjectDelivery subjectDelivery, InstructorAssignmentRole role) {
			var result = new InstructorAssignment(teacher, subjectDelivery, role);
		    return result;
		}
コード例 #56
0
        public ActionResult details(int id)
        {
            Instructor s = db.Instructors.Where(n => n.Ins_Id == id).FirstOrDefault();

            return(View(s));
        }
コード例 #57
0
        private void PopulateAssignedCourseData(Instructor instructor)
        {
            var allCourses = db.Courses;
            var instructorCourses = new HashSet<int>(instructor.Courses.Select(c=>c.CourseID));
            var viewModel = new List<AssignedCourseData>();

            foreach(var course in allCourses)
            {
                viewModel.Add(new AssignedCourseData
                {
                    CourseID = course.CourseID,
                    Title = course.Title,
                    Assigned = instructorCourses.Contains(course.CourseID)
                });
            }

            ViewBag.Courses = viewModel;
        }
コード例 #58
0
ファイル: FileController.cs プロジェクト: 1000VIA/SRA
        public IHttpActionResult UploadFile()
        {
            Model1 entity = new Model1();

            try
            {
                //                List<LogResponseDTO> lstErrores = new List<LogResponseDTO>();
                var httpRequest = HttpContext.Current.Request;
                if (httpRequest.Files.Count > 0)
                {
                    var fileSavePath = string.Empty;

                    var docfiles = new List <string>();

                    var URLArchivo = "";

                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];
                        //var filePath = HttpContext.Current.Server.MapPath("/UploadedFiles/");
                        var filePath = "C:/UploadedFiles/";

                        var GUID = Guid.NewGuid().ToString();

                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        fileSavePath = Path.Combine(filePath, GUID + "." + postedFile.FileName.Split('.')[1]);



                        postedFile.SaveAs(fileSavePath);

                        docfiles.Add(filePath);

                        URLArchivo = "C:/UploadedFiles/" + GUID + "." + postedFile.FileName.Split('.')[1];


                        string e = Path.GetExtension(URLArchivo);
                        if ((e != ".xlsx") && (e != ".xlsm"))
                        {
                            return(Ok(new { success = false, message = "La extencion del archivo no es valida" }));
                        }
                    }


                    InstructorBl instructor = new InstructorBl();

                    var book = new ExcelQueryFactory(URLArchivo);

                    var hoja      = book.GetWorksheetNames();
                    var resultado = (from i in book.Worksheet(hoja.FirstOrDefault())
                                     select i).ToList();

                    foreach (var values in resultado)
                    {
                        Instructor oInstructor = new Instructor();
                        var        cedula      = instructor.ConsultarInstructorCedula(values[2]);
                        if (cedula == null)
                        {
                            oInstructor.Nombre   = values[0];
                            oInstructor.Apellido = values[1];
                            oInstructor.Cedula   = values[2];
                            oInstructor.Email    = values[3];
                            oInstructor.Estado   = true;
                            oInstructor.Telefono = values[4];

                            var codigo = int.Parse(values[5]);
                            var area   = (from i in entity.Area
                                          where i.Codigo == codigo
                                          select i).FirstOrDefault();

                            if (values[6].ToString().ToLower() == "contratista")
                            {
                                oInstructor.TipoContrato = "1";
                            }
                            else
                            {
                                oInstructor.TipoContrato = "2";
                            }
                            //oInstructor.IdCompetencia = int.Parse(values[4]);

                            ProgramaBl oProgramaBl = new ProgramaBl();

                            // oListaInstructor.Add(oInstructor);

                            instructor.GuardarInstructor(oInstructor);
                        }
                    }
                    return(Ok(new { success = true, path = URLArchivo, }));
                }
                else
                {
                    return(Ok(new { success = false, message = "No File" }));
                }
            }
            catch (Exception exc)
            {
                return(Ok(new { success = false, message = exc.Message }));
            }
        }
コード例 #59
0
 public void AddInstructor(Instructor instructor)
 {
     _instructors = _context.db.GetCollection <Instructor>(_instructorsCollectionName);
     _instructors.InsertOne(instructor);
 }
        static void Main(string[] args)
        {
            //PRUEBA TUTOR

            //Declaracion de listas para Tutor.

            List <Tutor> ListadosDeTutores  = new List <Tutor>();
            List <Tutor> ListadosDelUsuario = new List <Tutor>();

            //Conexion a la base de Datos.

            ConexionTutor C = new ConexionTutor();

            C.conectar();
            Console.ReadKey();

            //Creacion del objeto Tutor.

            //Tutor TutorNuevo = new Tutor("SergioFF", "GONZALESFF", 12344, "Prueba4");
            //Tutor TutorNuevo2 = new Tutor(25, "Daniel", "Fernandez", 22222, "Prueba22");
            //Console.WriteLine(TutorNuevo.ToString());
            // Console.ReadKey();

            //Ingresar Tutor a la Base de Datos.

            // Console.WriteLine(C.insertarTutor(TutorNuevo));
            // Console.ReadKey();

            //Eliminacion de un Tutor en la Base de Datos determinado por su ID.

            /*Console.WriteLine(C.eliminar(4));
             * Console.ReadKey();*/

            //Actualizacion de un registro Tutor ya ingresado.

            /*Console.WriteLine(C.actualizar(TutorNuevo2));
             * Console.ReadKey();*/

            //Recuperar registros de un usuario determinado por su DNI.

            /*ListadosDelUsuario = C.RetornarUsuario(2);
             *
             * //Listado de los registros del usuario recuperados anteriormente.
             *
             * Console.WriteLine("Listado del Usuario: \n");
             *
             * foreach (Tutor X in ListadosDelUsuario)
             * {
             *  Console.WriteLine(X.getTutor());
             * }
             * Console.ReadKey();*/

            //Recuperacion de registros de todos los registros de la tabla Tutor.

            ListadosDeTutores = C.RetornarTablaTutor();

            //Listado de los registros de Tutores recuperados anteriormente.

            Console.WriteLine("Listado de Tutores: \n");

            foreach (Tutor X in ListadosDeTutores)
            {
                Console.WriteLine(X.getTutor());
                C.RetornarTablaTutor();
            }
            Console.ReadKey();

            //-----------------------------------------------------------------------------------------------------

            //PRUEBA INSTRUCTOR

            //Declaracion de listas para Tutor.

            List <Instructor> ListadosDeInstructores = new List <Instructor>();
            List <Instructor> ListadosDelUsuario2    = new List <Instructor>();

            //Conexion a la base de datos.

            ConexionInstructor C2 = new ConexionInstructor();

            C2.conectar();
            Console.ReadKey();

            //Creacion del objeto Instructor.
            Instructor InstructorNuevo = new Instructor("Martin", "Quintana", 33333555, "Prueba Instruc");

            Console.WriteLine("\n" + InstructorNuevo.ToString());
            Console.ReadKey();

            //Ingreso Instructor a la base de datos.

            Console.WriteLine(C2.insertarInstructor(InstructorNuevo));
            Console.ReadKey();

            //Eliminacion de un Instructor en la Base de Datos determinado por su ID.

            /*Console.WriteLine(C2.eliminar(5));
             * Console.ReadKey();*/

            //Actualizacion de un registro Instructor ya ingresado.

            /*Console.WriteLine(C2.actualizar(InstructorNuevo));
             * Console.ReadKey();*/

            //Recuperar registros de un usuario determinado por su DNI.

            /*ListadosDelUsuario = C.RetornarUsuario(2);
             *
             * //Listado de los registros del usuario recuperados anteriormente.
             *
             * Console.WriteLine("Listado del Usuario: \n");
             *
             * foreach (Tutor X in ListadosDelUsuario)
             * {
             *  Console.WriteLine(X.getTutor());
             * }
             * Console.ReadKey();*/

            //Recuperacion de registros de todos los registros de la tabla Instructor.

            ListadosDeInstructores = C2.RetornarTablaInstructor();

            //Listado de los registros de Instructores recuperados anteriormente.

            Console.WriteLine("Listado de Instructores: \n");

            foreach (Instructor X in ListadosDeInstructores)
            {
                Console.WriteLine(X.getInstructor());
            }
            Console.ReadKey();

            //------------------------------------------------------------------------------

            //PRUEBA CONTRATO

            //Declaracion de listas para Contrato.

            List <Contrato> ListadosDeContratos = new List <Contrato>();
            List <Contrato> ListadosDelUsuario3 = new List <Contrato>();
        }