Beispiel #1
0
 public CohortVM(CohortDTO row)
 {
     Id      = row.Id;
     Name    = row.Name;
     Root    = row.Root;
     Sorting = row.Sorting;
 }
Beispiel #2
0
        public string AddNewCohort(string catName)
        {
            string id;

            using (Db db = new Db())
            {
                if (db.Cohorts.Any(x => x.Name == catName))
                {
                    return("titletaken");
                }

                CohortDTO dto = new CohortDTO();

                dto.Name    = catName;
                dto.Root    = catName.Replace(" ", "-").ToLower();
                dto.Sorting = 100;

                db.Cohorts.Add(dto);
                db.SaveChanges();

                id = dto.Id.ToString();
            }

            return(id);
        }
        } // End of AddCohort

        /// <summary>
        /// Business logic for modifying Cohort records
        /// </summary>
        /// <param name="cohort"></param>
        /// <returns></returns>
        internal object ModifyCohortBLL(CohortDTO cohort)
        {
            // Create a new APIException object to store possible exceptions as checks are performed.
            APIException exceptionList = new APIException();

            // Check if the id matches a CohortID already in the database.
            if (!CohortExists(cohort.CohortID))
            {
                exceptionList.AddExMessage($"Cohort does not exist with the ID {cohort.CohortID}");
            }
            else
            {
                // Check if the supplied changes meet requirements as for addition
                if (cohort.Name == null || cohort.Name.Trim() == string.Empty)
                {
                    exceptionList.AddExMessage("Name parameter cannot be empty.");
                }
                else
                {
                    // Check if a cohort with the same name exists in the database (trim + case insensitive)
                    // If it does, it has to have a different CohortID from the one supplied (i.e. ignore if they have the same ID)
                    bool dbContainsName = _context.Cohorts.Any(x => (x.Name.ToLower() == cohort.Name.Trim().ToLower()) && (x.CohortID != cohort.CohortID));

                    if (dbContainsName)
                    {
                        exceptionList.AddExMessage("A cohort with the same name already exists in the database.");
                    }

                    // Check that the startDate is less than endDate
                    bool datesConsistent = cohort.StartDate < cohort.EndDate;
                    if (!datesConsistent)
                    {
                        exceptionList.AddExMessage("Start date must be before the end date, check for consistency.");
                    }
                }
            }

            if (!exceptionList.HasExceptions)
            {
                // New database name will be trimmed and in Proper Case.
                string dbName = String.Join(" ", cohort.Name.Trim().Split(" ").Select(x => $"{x.Substring(0, 1).ToUpper()}{x.Substring(1)?.ToLower()}").ToArray());

                // Create a new Cohort object
                Cohort newDbObject = new Cohort {
                    CohortID = cohort.CohortID, Name = dbName, StartDate = cohort.StartDate, EndDate = cohort.EndDate
                };

                // Return the Cohort object (conversion from CohortDTO for internal ops)
                return(newDbObject);
            }
            else
            {
                return(exceptionList);
            }
        } // End of ModifyCohort
        public async Task <ActionResult> ModifyCohort([FromBody] CohortDTO cohort)
        {
            if (CohortExists(cohort.CohortID))
            {
                // Call BLL Cohort Add method with all the parameters
                object BLLResponse = new CohortBLL(_context).ModifyCohortBLL(cohort: cohort);

                // Get the base class for the response
                // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.type.basetype?view=netcore-3.1
                if (BLLResponse.GetType().BaseType == typeof(Exception))
                {
                    // Create log entries for Debug log
                    ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <CohortsController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

                    // Return response from API
                    return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() }));
                }
                else
                {
                    try
                    {
                        // Find the existing record based on ID
                        Cohort currentRecord = _context.Cohorts.Where(x => x.CohortID == cohort.CohortID).First();

                        // Modify the record
                        currentRecord.Name      = ((Cohort)BLLResponse).Name;
                        currentRecord.StartDate = ((Cohort)BLLResponse).StartDate;
                        currentRecord.EndDate   = ((Cohort)BLLResponse).EndDate;

                        // Save changes
                        await _context.SaveChangesAsync();

                        Logger.Msg <CohortsController>($"[{User.FindFirstValue("email")}] [MODIFY] CohortID: {currentRecord.CohortID} successful", Serilog.Events.LogEventLevel.Information);

                        // Return modified record as a DTO
                        CohortDTO response = new CohortDTO(currentRecord);
                        return(Ok(response));
                    }
                    catch (Exception ex)
                    {
                        // Local log entry. Database reconciliation issues are more serious so reported as Error
                        Logger.Msg <CohortsController>($"[MODIFY] Database sync error {ex.Message}", Serilog.Events.LogEventLevel.Error);

                        // Return response to client
                        return(StatusCode(500, new { errors = "Database update failed. Contact the administrator to resolve this issue." }));
                    }
                }
            }
            else
            {
                return(NotFound());
            }
        } // End of ModifyCohort
Beispiel #5
0
        public ActionResult DeleteCohort(int id)
        {
            using (Db db = new Db())
            {
                CohortDTO dto = db.Cohorts.Find(id);

                db.Cohorts.Remove(dto);

                db.SaveChanges();
            }

            return(RedirectToAction("Cohorts"));
        }
Beispiel #6
0
        public string RenameCohort(string newCatName, int id)
        {
            using (Db db = new Db())
            {
                if (db.Cohorts.Any(x => x.Name == newCatName))
                {
                    return("titletaken");
                }

                CohortDTO dto = db.Cohorts.Find(id);

                dto.Name = newCatName;
                dto.Root = newCatName.Replace(" ", "-").ToLower();

                db.SaveChanges();
            }

            return("test");
        }
        public async Task <ActionResult> AddCohort(string name, DateTime startDate, DateTime endDate)
        {
            // This will by default check if there is Authorization to execute. If there isn't an authorization, then API server automatically
            // returns 401 response.

            // Call BLL Cohort Add method with all the parameters
            object BLLResponse = new CohortBLL(_context).AddCohortBLL(name: name, startDate: startDate, endDate: endDate);

            // Get the base class for the response
            // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.type.basetype?view=netcore-3.1
            if (BLLResponse.GetType().BaseType == typeof(Exception))
            {
                // Create log entries for Debug log
                ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <CohortsController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

                // Return response from API
                return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() }));
            }
            else
            {
                try
                {
                    _context.Cohorts.Add((Cohort)BLLResponse);

                    await _context.SaveChangesAsync();

                    Logger.Msg <CohortsController>($"[{User.FindFirstValue("email")}] [ADD] '{name}' successful", Serilog.Events.LogEventLevel.Information);
                    CohortDTO response = new CohortDTO((Cohort)BLLResponse);
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    // Local log entry. Database reconciliation issues are more serious so reported as Error
                    Logger.Msg <CohortsController>($"[ADD] Database sync error {ex.Message}", Serilog.Events.LogEventLevel.Error);

                    // Return response to client
                    return(StatusCode(500, new { errors = "Database update failed. Contact the administrator to resolve this issue." }));
                }
            }
        } // End of AddCohort
Beispiel #8
0
        public ActionResult AddStudent(StudentVM model, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            using (Db db = new Db())
            {
                if (db.Student.Any(x => x.FirstName == model.FirstName))
                {
                    model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Sorry! That student name is taken!");
                    return(View(model));
                }
            }

            int id;

            using (Db db = new Db())
            {
                StudentDTO student = new StudentDTO();

                student.FirstName = model.FirstName;
                student.LastName  = model.LastName;
                student.Root      = model.FirstName.Replace(" ", "-").ToLower();
                student.CohortId  = model.CohortId;

                CohortDTO catDTO = db.Cohorts.FirstOrDefault(x => x.Id == model.CohortId);
                student.CohortName = catDTO.Name;

                db.Student.Add(student);
                //db.SaveChanges();

                id = student.Id;
            }

            TempData["SM"] = "Successfully added a student!";

            #region Upload Image

            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

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

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

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

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

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

            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Cohorts = new SelectList(db.Cohorts.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "ERROR: The image was not uploaded - wrong image extension.");
                        return(View(model));
                    }
                }

                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    StudentDTO dto = db.Student.Find(id);
                    if (dto != null)
                    {
                        dto.ImageName = imageName;
                    }

                    db.SaveChanges();
                }

                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            return(RedirectToAction("AddStudent"));
        }