} // End of GetNoticeBLL

        /// <summary>
        /// Business logic for processing Notice record addition
        /// </summary>
        /// <param name="notice"></param>
        /// <returns></returns>
        internal object AddNoticeBLL(NoticeDTO notice, ClaimsPrincipal userClaims)
        {
            // Get the StaffID of the currently logged in Staff member
            int loggedInStaffID = _context.Users.Where(x => x.Email == userClaims.FindFirst("Email").Value).Include(user => user.StaffData).Select(x => x.StaffData.StaffID).FirstOrDefault();

            // Create a new APIException object to store possible exceptions as checks are performed.
            APIException exceptionList = new APIException();

            Dictionary <string, bool> exceptionTests = new Dictionary <string, bool>()
            {
                { "cohortID must be valid", notice.CohortID != 0 && !_context.Cohorts.Any(x => x.CohortID == notice.CohortID) },
                { "staffID must be valid", notice.StaffID != 0 && !_context.Staff.Any(x => x.StaffID == notice.StaffID) },
                { "Notice text should not be null or empty", string.IsNullOrEmpty(notice.HTML.Trim()) || string.IsNullOrEmpty(notice.Markdown.Trim()) }
            };

            foreach (KeyValuePair <string, bool> kvp in exceptionTests)
            {
                if (kvp.Value)
                {
                    exceptionList.AddExMessage(kvp.Key);
                }
            }

            if (!exceptionList.HasExceptions)
            {
                notice.StaffID = loggedInStaffID;

                return(notice);
            }
            else
            {
                return(exceptionList);
            }
        } // End of AddNoticeBLL
示例#2
0
        public NoticeDTO GetNotice(int?noticeID)
        {
            SqlDatabase db = DatabaseFactory.CreateDatabase() as SqlDatabase;

            if (db == null)
            {
                throw new Exception("Do poprawnego działania wymagany jest SQL Server 2005!");
            }

            NoticeDTO notice = null;
            DbCommand cmd    = db.GetStoredProcCommand("Uzytkownicy.pobierzKomunikat", noticeID);

            using (IDataReader dr = db.ExecuteReader(cmd))
            {
                if (dr.Read())
                {
                    notice = new NoticeDTO(
                        int.Parse(dr["id"].ToString()),
                        dr["notice"].ToString(),
                        String.IsNullOrEmpty(dr["startDate"].ToString()) ? null : (DateTime?)(dr["startDate"]),
                        String.IsNullOrEmpty(dr["endDate"].ToString()) ? null : (DateTime?)(dr["endDate"]),
                        bool.Parse(dr["isActive"].ToString()));
                }
            };

            return(notice);
        }
示例#3
0
        public async Task <ActionResult> GetModel(long id)
        {
            NoticeDTO model = await noticeService.GetModelAsync(id);

            return(Json(new AjaxResult {
                Status = 1, Data = model
            }));
        }
示例#4
0
        public string ImportMovie(HttpPostedFileBase uploadName, DateTime Start_Time, DateTime End_Time, string Scope, int?RepeatTime)
        {
            string errorInfo = string.Empty;
            string name      = uploadName.FileName;
            string extName   = name.Split('.')[1].ToLower();

            if (extName != "mp4")
            {
                return("必须是mp4格式文件,请返回后重传!");
            }
            if (uploadName == null)
            {
                return("没有文件!");
            }

            var severURL = "~/Movie/" + Path.GetFileName(uploadName.FileName);//severURL
            var fileName = Path.Combine(Request.MapPath("~/Movie"), Path.GetFileName(uploadName.FileName));

            try
            {
                uploadName.SaveAs(fileName);
            }
            catch (Exception ex)
            {
                return("上传异常 ! " + "   " + ex);
            }

            //上传成功后将数据写入数据表
            var apiUrl = "Chart/AddNoticeAPI";
            var entity = new NoticeDTO();

            entity.Start_Time  = Start_Time;
            entity.End_Time    = End_Time;
            entity.Creator_UID = CurrentUser.AccountUId;
            entity.Creat_Time  = DateTime.Now;
            if (DateTime.Compare(entity.Creat_Time, entity.Start_Time) < 0)
            {
                entity.State = "未开始";
            }

            else if (DateTime.Compare(entity.Creat_Time, entity.Start_Time) >= 0 && DateTime.Compare(entity.Creat_Time, entity.End_Time) <= 0)
            {
                entity.State = "进行中";
            }
            else if (DateTime.Compare(entity.Creat_Time, entity.End_Time) > 0)
            {
                entity.State = "已过时";
            }
            entity.Color          = "视频";
            entity.Notice_Content = "../Movie/" + Path.GetFileName(uploadName.FileName) + "$" + fileName;
            entity.Scope          = Scope;

            entity.RepeatTime = RepeatTime;
            HttpResponseMessage responMessage = APIHelper.APIPostAsync(entity, apiUrl);
            var result = responMessage.Content.ReadAsStringAsync().Result;

            return("上传成功");
        }
示例#5
0
        public async Task <ActionResult <IEnumerable <NoticeDTO> > > Get(int noticeID, int cohortID, int staffID, DateTime validFrom)
        {
            // Check if the current user is a staff member (or Super Admin)
            bool isUserStaff = User.IsInRole("Staff") || User.IsInRole("SuperAdmin");

            // Call GetNoticekBLL method with all the parameters
            object BLLResponse = new NoticeBLL(_context).GetNoticeBLL(noticeID: noticeID, cohortID: cohortID, staffID: staffID, validFrom: validFrom, isUserStaff: isUserStaff);

            // 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 <NoticesController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

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

                    // Apply all the criteria with supplied or default values from BLL. Limit Student access to notices issued up to current date.
                    IQueryable <Notice> dbRequest = _context.Notices
                                                    .Where(x => x.ValidFrom >= BLLResponseDTO.ValidFrom && (isUserStaff || x.ValidFrom <= DateTime.Today));

                    if (BLLResponseDTO.CohortID != 0)
                    {
                        dbRequest = dbRequest.Where(x => x.CohortID == BLLResponseDTO.CohortID);
                    }
                    if (BLLResponseDTO.StaffID != 0 && isUserStaff)
                    {
                        dbRequest = dbRequest.Where(x => x.StaffID == BLLResponseDTO.StaffID);
                    }

                    List <Notice> dbResponse = await dbRequest.ToListAsync();

                    // Convert result to TaskDTO
                    List <NoticeDTO> response = new List <NoticeDTO>();
                    dbResponse.ForEach(x => response.Add(new NoticeDTO(x)));

                    Logger.Msg <NoticesController>($"[{User.FindFirstValue("email")}] [GET] ", Serilog.Events.LogEventLevel.Debug);
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    // Local log entry. Database reconciliation issues are more serious so reported as Error
                    Logger.Msg <TasksController>($"[GET] 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 Get
示例#6
0
        public async Task <ActionResult> ModifyNotice([FromBody] NoticeDTO notice)
        {
            if (NoticeExists(notice.NoticeID))
            {
                // Call BLL Notice Modify method with all the parameters
                object BLLResponse = new NoticeBLL(_context).ModifyNoticeBLL(notice: notice, userClaims: User);

                if (BLLResponse.GetType().BaseType == typeof(Exception))
                {
                    // Create log entries for Debug log
                    ((APIException)BLLResponse).Exceptions.ForEach(ex => Logger.Msg <NoticesController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

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

                        // Find the existing record based on ID
                        Notice currentRecord = _context.Notices.Where(x => x.NoticeID == modNotice.NoticeID).First();

                        // Modify the record
                        currentRecord.HTML      = modNotice.HTML;
                        currentRecord.Markdown  = modNotice.Markdown;
                        currentRecord.ValidFrom = modNotice.ValidFrom;
                        currentRecord.StaffID   = modNotice.StaffID;

                        // Save changes
                        await _context.SaveChangesAsync();

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

                        // Return modified record as a DTO
                        NoticeDTO response = new NoticeDTO(currentRecord);
                        return(Ok(response));
                    }
                    catch (Exception ex)
                    {
                        // Local log entry. Database reconciliation issues are more serious so reported as Error
                        Logger.Msg <TaskTypesController>($"[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 ModifyNotice
示例#7
0
        public async Task <ActionResult> AddNotice(NoticeDTO notice)
        {
            // Call BLL Notice Add method with all the parameters
            object BLLResponse = new NoticeBLL(_context).AddNoticeBLL(notice: notice, userClaims: User);

            // 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 <NoticesController>((Exception)ex, Serilog.Events.LogEventLevel.Debug));

                // Return response from API
                return(BadRequest(new { errors = ((APIException)BLLResponse).Exceptions.Select(x => x.Message).ToArray() }));
            }
            else
            {
                try
                {
                    // Convert BLLResponse to NoticeDTO object
                    NoticeDTO newNoticeDTO = (NoticeDTO)BLLResponse;

                    // Create a new Notice object
                    Notice newNotice = new Notice
                    {
                        HTML      = newNoticeDTO.HTML,
                        Markdown  = newNoticeDTO.Markdown,
                        CohortID  = newNoticeDTO.CohortID,
                        StaffID   = newNoticeDTO.StaffID,
                        ValidFrom = newNoticeDTO.ValidFrom
                    };

                    // Create the record
                    _context.Notices.Add(newNotice);
                    await _context.SaveChangesAsync();

                    Logger.Msg <NoticesController>($"[{User.FindFirstValue("email")}] [ADD] Notice '{newNotice.NoticeID}' successful", Serilog.Events.LogEventLevel.Information);

                    // Convert back to DTO and return to user
                    NoticeDTO response = new NoticeDTO(newNotice);
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    // Local log entry. Database reconciliation issues are more serious so reported as Error
                    Logger.Msg <NoticesController>($"[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 AddNotice
示例#8
0
        private NoticeDTO ToDTO(NoticeEntity entity)
        {
            NoticeDTO dto = new NoticeDTO();

            dto.CreateTime  = entity.CreateTime;
            dto.Id          = entity.Id;
            dto.Code        = entity.Code;
            dto.Content     = entity.Content;
            dto.FailureTime = entity.FailureTime;
            dto.IsEnabled   = entity.IsEnabled;
            dto.Url         = entity.Url;
            return(dto);
        }
示例#9
0
        public string AddNoticeAPI(NoticeDTO dto)
        {
            var ent = AutoMapper.Mapper.Map <Notice>(dto);

            var plantstring = ChartService.AddNotice(ent);

            if (plantstring != "SUCCESS")
            {
                return(plantstring);
            }
            else
            {
                return("SUCCESS");
            }
        }
示例#10
0
        public NoticeDTO ToDTO(NoticeEntity entity)
        {
            NoticeDTO dto = new NoticeDTO();

            dto.CreateTime  = entity.CreateTime;
            dto.Enabled     = entity.Enabled;
            dto.Content     = entity.Content;
            dto.Creator     = entity.Creator;
            dto.FailureTime = entity.FailureTime;
            dto.Id          = entity.Id;
            dto.Tip         = entity.Tip;
            dto.Title       = entity.Title;
            dto.Url         = entity.Url;
            return(dto);
        }
        /// <summary>
        /// Business logic for retrieving Notice records
        /// </summary>
        /// <param name="noticeID"></param>
        /// <param name="cohortID"></param>
        /// <param name="staffID"></param>
        /// <param name="validFrom"></param>
        /// <param name="isUserStaff"></param>
        /// <returns></returns>
        internal object GetNoticeBLL(int noticeID, int cohortID, int staffID, DateTime validFrom, bool isUserStaff)
        {
            // Create a new APIException object to store possible exceptions as checks are performed.
            APIException exceptionList = new APIException();

            Dictionary <string, bool> exceptionTests = new Dictionary <string, bool>()
            {
                { "noticeID must be valid", noticeID != 0 && !_context.Notices.Any(x => x.NoticeID == noticeID) },
                { "cohortID must be valid", cohortID != 0 && !_context.Cohorts.Any(x => x.CohortID == cohortID) },
                { "staffID must be valid", staffID != 0 && !_context.Staff.Any(x => x.StaffID == staffID) },
                { "validFrom date cannot be in the future", !(validFrom <= DateTime.Today) && !isUserStaff }
            };

            foreach (KeyValuePair <string, bool> kvp in exceptionTests)
            {
                if (kvp.Value)
                {
                    exceptionList.AddExMessage(kvp.Key);
                }
            }

            if (!exceptionList.HasExceptions)
            {
                // Apply defaults
                if (validFrom == DateTime.MinValue)
                {
                    validFrom = _context.Cohorts.Where(x => x.CohortID == cohortID).First().StartDate;
                }


                NoticeDTO getParams = new NoticeDTO
                {
                    NoticeID  = noticeID,
                    CohortID  = cohortID,
                    StaffID   = staffID,
                    ValidFrom = validFrom
                };

                return(getParams);
            }
            else
            {
                return(exceptionList);
            }
        } // End of GetNoticeBLL
示例#12
0
 private void LoadNotice()
 {
     try
     {
         NoticeDTO notice = dao.GetNotice(NoticeID);
         if (notice != null)
         {
             NoticeID           = notice.NoticeID;
             tbNotice.Text      = notice.Notice;
             tbEndDate.Text     = notice.EndDate.HasValue ? notice.EndDate.Value.ToShortDateString() : string.Empty;
             tbStartDate.Text   = notice.StartDate.HasValue ? notice.StartDate.Value.ToShortDateString() : string.Empty;
             cbIsActive.Checked = notice.IsActive;
         }
     }
     catch (Exception ex)
     {
         lblMessage.Text = ex.Message;
     }
 }