コード例 #1
0
ファイル: TestHarness.cs プロジェクト: ilikemyname/Csharp
        private void TestEditClass()
        {
            Course      course      = cc.SearchCourse("cosc2323");
            Lecturer    lecturer    = lc.SearchLecturer("v3222222");
            string      className   = course.Id + "-" + lecturer.Id;
            Class       aClass      = clc.SearchClass(className);
            DateTime    startTime   = DateTime.Parse("16:30");
            DateTime    endTime     = DateTime.Parse("18:00");
            Room        room        = rc.SearchRoom("1.1.2");
            string      dayOfWeek   = "Monday";
            ClassPeriod classPeriod = new ClassPeriod(room, dayOfWeek, startTime, endTime);

            clc.DeleteClassName(className);
            if (clc.ConflictTime(classPeriod))
            {
                Console.WriteLine("Fail! This class has period that clashed with following class: ");
                Console.WriteLine("\t\t(Class name ({0})): ", course.Id + "-" + lecturer.Id);
                Console.WriteLine("\tClass period: {0}", classPeriod.ToString());
            }
            else
            {
                clc.CreateClass(course, lecturer, classPeriod);
                Console.WriteLine("Pass! This class is updated, no period conflicted.");
                Console.WriteLine("\t\t(Class name ({0})): ", course.Id + "-" + lecturer.Id);
                Console.WriteLine("\tClass period: {0}", classPeriod.ToString());
            }
        }
コード例 #2
0
        public async Task <ActionResult <ClassPeriod> > PostClassPeriod(ClassPeriod classPeriod)
        {
            _context.ClassPeriods.Add(classPeriod);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetClassPeriod", new { id = classPeriod.ClassPeriodId }, classPeriod));
        }
コード例 #3
0
        internal bool ConflictLecturer(string lid, ClassPeriod classPeriod)
        {
            lid = lid.ToLower();
            Room room = classPeriod.Room;
            bool cf   = false;

            foreach (KeyValuePair <string, Class> KeyValOfClass in classList)
            {
                string lecturerId = KeyValOfClass.Value.Lecturer.Id;
                foreach (ClassPeriod cp in KeyValOfClass.Value.ClassPeriodList)
                {
                    if (lecturerId.Equals(lid))
                    {
                        cf = false;
                        cf = cp.TimeConflict(classPeriod);
                        if (cf)
                        {
                            break;
                        }
                    }
                }
                if (cf)
                {
                    break;
                }
            }
            return(cf);
        }
コード例 #4
0
        public async Task <ActionResult <ClassPeriod> > CreateClassPeriod(ClassPeriod classPeriod)
        {
            _logger.LogInformation("Creating Class Period {@ClassPeriod} at {RequestTime}", classPeriod, DateTime.UtcNow);

            try
            {
                classPeriod = await _service.CreateAsync(classPeriod.Name);

                return(CreatedAtAction(
                           nameof(GetClassPeriod),
                           new { id = classPeriod.Id },
                           classPeriod
                           ));
            }
            catch (DuplicateClassPeriodException ex)
            {
                ModelState.AddModelError(nameof(classPeriod.Name), ex.Message);
                return(BadRequest(ModelState)); // TODO: return ValidationProblem instead?
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Creating Class Period {@ClassPeriod} failed", classPeriod);
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError));
        }
コード例 #5
0
        public async Task <IActionResult> PutClassPeriod(int id, ClassPeriod classPeriod)
        {
            if (id != classPeriod.ClassPeriodId)
            {
                return(BadRequest());
            }

            _context.Entry(classPeriod).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClassPeriodExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #6
0
        public void AddStudent_TrimsWhitespace(string original, string expected)
        {
            var cp = new ClassPeriod();

            cp.AddStudent(original);
            cp.Students.First().Name.Should().Be(expected);
        }
コード例 #7
0
ファイル: TestHarness.cs プロジェクト: ilikemyname/Csharp
        private void TestAddClass()
        {
            Console.WriteLine("Testing Add Class");
            Console.WriteLine();
            Console.WriteLine("\t\t\t\tAdding class no conflict to others");
            Course      course      = cc.SearchCourse("cosc2323");
            Lecturer    lecturer    = lc.SearchLecturer("v3222222");
            Room        room        = rc.SearchRoom("1.1.2");
            DateTime    startTime   = DateTime.Parse("8:00");
            DateTime    endTime     = DateTime.Parse("9:00");
            string      dayOfWeek   = "monday";
            ClassPeriod classPeriod = new ClassPeriod(room, dayOfWeek, startTime, endTime);

            for (int i = 0; i < 2; i++)
            {
                if (clc.ConflictTime(classPeriod))
                {
                    Console.WriteLine("Fail! This class has period that clashed with following class: ");
                    Console.WriteLine("\t\t(Class name ({0})): ", course.Id + "-" + lecturer.Id);
                    Console.WriteLine("\tClass period: {0}", classPeriod.ToString());
                }
                else
                {
                    clc.CreateClass(course, lecturer, classPeriod);
                    Console.WriteLine("Pass! This class is added, no period conflicted.");
                }
            }
            Console.WriteLine();
        }
コード例 #8
0
        public async Task AddStudentsToClassAlreadyContainingStudents()
        {
            var orig = await GivenAClassPeriodWithStudents("Add Students: Justice League of America", "Batman", "Killer Frost");

            var request = new ClassPeriod
            {
                Id       = orig.Id,
                Name     = orig.Name,
                Students = new List <Student>
                {
                    new Student {
                        Name = "Batman"
                    },
                    new Student {
                        Name = "Killer Frost"
                    }
                }
            };

            await WhenIAddStudents(request, "Black Canary", "Vixen", "The Atom", "The Ray", "Lobo");

            ThenTheseStudentsAreInTheClassPeriod(orig,
                                                 "Batman",
                                                 "Killer Frost",
                                                 "Black Canary",
                                                 "Vixen",
                                                 "The Atom",
                                                 "The Ray",
                                                 "Lobo"
                                                 );
        }
コード例 #9
0
        internal bool ConflictTime(ClassPeriod classPeriod)
        {
            string room = classPeriod.Room.RoomNo;

            bool conflict = false;

            foreach (KeyValuePair <string, Class> KeyValOfClass in classList)
            {
                //string lecturerId = KeyValOfClass.Value.Lecturer.Id;
                foreach (ClassPeriod cp in KeyValOfClass.Value.ClassPeriodList)
                {
                    string alreadyRoom = cp.Room.RoomNo;

                    if (room.Equals(alreadyRoom))
                    {
                        conflict = false;
                        //conflict = Validate.TimeConFlict(classPeriod, cp);
                        conflict = cp.TimeConflict(classPeriod);
                        if (conflict)
                        {
                            break;
                        }
                    }
                }
                if (conflict)
                {
                    break;
                }
            }
            return(conflict);
        }
コード例 #10
0
        /// <summary>
        /// Updates or creates a resource based on the resource identifier. The PUT operation is used to update or create a resource by identifier.  If the resource doesn't exist, the resource will be created using that identifier.  Additionally, natural key values cannot be changed using this operation, and will not be modified in the database.  If the resource &quot;id&quot; is provided in the JSON body, it will be ignored as well.
        /// </summary>
        /// <param name="id">A resource identifier specifying the resource to be updated.</param>
        /// <param name="IfMatch">The ETag header value used to prevent the PUT from updating a resource modified by another consumer.</param>
        /// <param name="body">The JSON representation of the &quot;classPeriod&quot; resource to be updated.</param>
        /// <returns>A RestSharp <see cref="IRestResponse"/> instance containing the API response details.</returns>
        public IRestResponse PutClassPeriod(string id, string IfMatch, ClassPeriod body)
        {
            var request = new RestRequest("/classPeriods/{id}", Method.PUT);

            request.RequestFormat = DataFormat.Json;

            request.AddUrlSegment("id", id);
            // verify required params are set
            if (id == null || body == null)
            {
                throw new ArgumentException("API method call is missing required parameters");
            }
            request.AddHeader("If-Match", IfMatch);
            request.AddBody(body);
            request.Parameters.First(param => param.Type == ParameterType.RequestBody).Name = "application/json";
            var response = client.Execute(request);

            var location = response.Headers.FirstOrDefault(x => x.Name == "Location");

            if (location != null && !string.IsNullOrWhiteSpace(location.Value.ToString()))
            {
                body.id = location.Value.ToString().Split('/').Last();
            }
            return(response);
        }
コード例 #11
0
        public void GiveTicketsToStudent_IgnoresNonPositiveNumbers(int tickets)
        {
            var cp = new ClassPeriod();

            cp.AddStudent("Black Canary");
            cp.GiveTicketsTo(cp.Students.Last(), tickets);
            cp.Students.Single().Tickets.Should().Be(0);
        }
コード例 #12
0
        public void AddStudent_UniqueName_Succeeds()
        {
            var cp = new ClassPeriod();

            cp.AddStudent("Black Canary");
            cp.AddStudent("Killer Frost");
            cp.Students.Select(s => s.Name).Should().BeEquivalentTo("Black Canary", "Killer Frost");
        }
コード例 #13
0
        public void AddStudent_DuplicateName_ThrowsException(string name)
        {
            var cp = new ClassPeriod();

            cp.AddStudent("Black Canary");
            Assert.ThrowsException <DuplicateStudentException>(() => cp.AddStudent(name));
            cp.Students.Count.Should().Be(1);
        }
コード例 #14
0
        public async Task ReturnsTheCreatedClassPeriod()
        {
            var expected = new ClassPeriod {
                Id = 1, Name = "Creation: 1"
            };
            var actual = await WhenICreateClassPeriod("Creation: 1");

            actual.Should().BeEquivalentTo(expected);
        }
コード例 #15
0
 protected ClassPeriodViewData(ClassPeriod classPeriod, Room room, ClassDetails classComplex)
     : base(classPeriod, room)
 {
     if (classComplex != null)
     {
         Class         = ClassViewData.Create(classComplex);
         StudentsCount = classComplex.StudentsCount;
     }
 }
コード例 #16
0
        public void GiveTicketsToStudent_StartValue3_AddsTickets()
        {
            var cp = new ClassPeriod();

            cp.Students.Add(new Student {
                Name = "Killer Frost", Tickets = 3
            });
            cp.GiveTicketsTo(cp.Students.Last(), 4);
            cp.Students.Single().Tickets.Should().Be(7);
        }
コード例 #17
0
        public void GiveTicketsToStudent_StartValue0_TotalTicketsEqualToHowManyGiven(int tickets)
        {
            var cp = new ClassPeriod();

            cp.Students.Add(new Student {
                Name = "Killer Frost"
            });
            cp.GiveTicketsTo(cp.Students.Last(), tickets);
            cp.Students.Last().Tickets.Should().Be(tickets);
        }
コード例 #18
0
 protected ClassPeriodShortViewData(ClassPeriod classPeriod, Room room)
 {
     Period     = PeriodViewData.Create(classPeriod.Period);
     ClassId    = classPeriod.ClassRef;
     DateTypeId = classPeriod.DayTypeRef;
     if (room != null)
     {
         RoomId     = room.Id;
         RoomNumber = room.RoomNumber;
     }
 }
コード例 #19
0
        public async Task GetSpecifiedClassPeriod()
        {
            var second = new ClassPeriod {
                Id = 2, Name = "Creation: 2"
            };

            await GivenIPreviouslyCreatedClassPeriod("Creation: 1");
            await GivenIPreviouslyCreatedClassPeriod("Creation: 2");

            var actual = await WhenIAskForTheSecondOne();

            ThenIGet(actual, second);
        }
コード例 #20
0
        public async Task AddStudent()
        {
            var orig = await GivenIPreviouslyCreatedClassPeriod("Add Students: Justice League of America");

            var request = new ClassPeriod
            {
                Id   = orig.Id,
                Name = orig.Name
            };

            await WhenIAddStudents(request, "Batman");

            ThenTheseStudentsAreInTheClassPeriod(orig, "Batman");
        }
コード例 #21
0
        public async Task <ClassPeriod> CreateAsync(string name)
        {
            if (classPeriods.Any(cp => cp.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
            {
                throw new DuplicateClassPeriodException(name);
            }

            var classPeriod = new ClassPeriod {
                Id = GetNextId(), Name = name
            };

            classPeriods.Add(classPeriod);
            return(await Task.FromResult(classPeriod));
        }
コード例 #22
0
        public async Task <ActionResult> UpdateClassPeriod(int id, ClassPeriod classPeriod)
        {
            _logger.LogInformation("Updating Class Period {Id} to {@ClassPeriod} at {RequestTime}", id, classPeriod, DateTime.UtcNow);
            try
            {
                await _service.UpdateAsync(classPeriod);

                return(NoContent());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Updating Class Period {Id} to {@ClassPeriod} failed", id, classPeriod);
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError));
        }
コード例 #23
0
        public virtual ActionResult Create(CreateModel createModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(createModel));
            }

            var classPeriod = new ClassPeriod();

            _createModelToClassPeriodMapper.Map(createModel, classPeriod);

            _genericRepository.Add(classPeriod);
            _genericRepository.Save();

            return(RedirectToAction(MVC.ClassPeriod.Index()));
        }
コード例 #24
0
        public void GiveTicketsToStudent_OnlyAffectsSpecifiedStudent()
        {
            var cp = new ClassPeriod();

            cp.Students.Add(new Student {
                Name = "Black Canary", Tickets = 2
            });
            cp.Students.Add(new Student {
                Name = "Killer Frost", Tickets = 3
            });

            cp.GiveTicketsTo(cp.Students.Last(), 4);

            cp.Students.First().Tickets.Should().Be(2, "this student should not have received any tickets");
            cp.Students.Last().Tickets.Should().Be(7);
        }
コード例 #25
0
        public async Task UpdateAsync(ClassPeriod classPeriod)
        {
            await Task.Delay(1);

            var match = classPeriods.Single(cp => cp.Id == classPeriod.Id);

            foreach (var student in classPeriod.Students)
            {
                if (!match.Students.Any(s => s.Name == student.Name))
                {
                    match.AddStudent(student.Name);
                }

                var matchStudent = match.Students.Single(s => s.Name == student.Name);
                matchStudent.Tickets = student.Tickets;
            }
        }
コード例 #26
0
        public async Task Background()
        {
            _sut = new ClassPeriodService();
            await GivenAClassPeriodWithStudents("Add Students: Justice League of America",
                                                "Batman",
                                                "Killer Frost",
                                                "Black Canary",
                                                "Vixen",
                                                "The Atom",
                                                "The Ray",
                                                "Lobo");

            _theBatmen = await GivenAClassPeriodWithStudents("Add Students: The Batmen",
                                                             "Batwoman",
                                                             "Red Robin",
                                                             "Spoiler",
                                                             "Orphan",
                                                             "Clayface");
        }
コード例 #27
0
        public bool CreateClass(Course course, Lecturer lecturer, ClassPeriod classPeriod)
        {
            Class aClass = new Class(lecturer, course);

            if (!classList.ContainsKey(course.Id + "-" + lecturer.Id))
            {
                aClass.AddPeriod(classPeriod);
                string className = course.Id;
                classList.Add(course.Id + "-" + lecturer.Id, aClass);
                return(true);
            }
            //else
            //{
            Class alreadyClass = classList[course.Id + "-" + lecturer.Id];

            alreadyClass.AddPeriod(classPeriod);
            classList[course.Id + "-" + lecturer.Id] = alreadyClass;
            return(true);
            //}
            //return false;
        }
コード例 #28
0
        /// <summary>
        /// Creates or updates resources based on the natural key values of the supplied resource. The POST operation can be used to create or update resources. In database terms, this is often referred to as an &quot;upsert&quot; operation (insert + update).  Clients should NOT include the resource &quot;id&quot; in the JSON body because it will result in an error (you must use a PUT operation to update a resource by &quot;id&quot;). The web service will identify whether the resource already exists based on the natural key values provided, and update or create the resource appropriately.
        /// </summary>
        /// <param name="body">The JSON representation of the &quot;classPeriod&quot; resource to be created or updated.</param>
        /// <returns>A RestSharp <see cref="IRestResponse"/> instance containing the API response details.</returns>
        public IRestResponse PostClassPeriods(ClassPeriod body)
        {
            var request = new RestRequest("/classPeriods", Method.POST);

            request.RequestFormat = DataFormat.Json;

            // verify required params are set
            if (body == null)
            {
                throw new ArgumentException("API method call is missing required parameters");
            }
            request.AddBody(body);
            var response = client.Execute(request);

            var location = response.Headers.FirstOrDefault(x => x.Name == "Location");

            if (location != null && !string.IsNullOrWhiteSpace(location.Value.ToString()))
            {
                body.id = location.Value.ToString().Split('/').Last();
            }
            return(response);
        }
コード例 #29
0
        public async Task CannotAddAStudentWithTheSameNameToTheSameClassPeriod()
        {
            var request = new ClassPeriod
            {
                Id       = _theBatmen.Id,
                Name     = _theBatmen.Name,
                Students = new List <Student>
                {
                    new Student {
                        Name = "Batwoman"
                    },
                    new Student {
                        Name = "Red Robin"
                    },
                    new Student {
                        Name = "Spoiler"
                    },
                    new Student {
                        Name = "Orphan"
                    },
                    new Student {
                        Name = "Clayface"
                    }
                }
            };

            Func <Task> mut = async() => await WhenIAddStudents(request, "Batwoman");

            await mut.Should().ThrowAsync <DuplicateStudentException>();

            ThenTheseStudentsAreInTheClassPeriod(_theBatmen,
                                                 "Batwoman",
                                                 "Red Robin",
                                                 "Spoiler",
                                                 "Orphan",
                                                 "Clayface");
        }
コード例 #30
0
        public async Task AddAStudentWithTheSameNameToADifferentClassPeriod()
        {
            var request = new ClassPeriod
            {
                Id       = _theBatmen.Id,
                Name     = _theBatmen.Name,
                Students = new List <Student>
                {
                    // Although Batwoman is already in the class period, purposefully leave out of the request.
                    // This enables us to mimic the server and request being out of sync
                    //new Student { Name = "Batwoman" },
                    new Student {
                        Name = "Red Robin"
                    },
                    new Student {
                        Name = "Spoiler"
                    },
                    new Student {
                        Name = "Orphan"
                    },
                    new Student {
                        Name = "Clayface"
                    }
                }
            };

            await WhenIAddStudents(request, "Batman");

            ThenTheseStudentsAreInTheClassPeriod(_theBatmen,
                                                 "Batwoman",
                                                 "Red Robin",
                                                 "Spoiler",
                                                 "Orphan",
                                                 "Clayface",
                                                 "Batman");
        }