コード例 #1
0
        public async Task <IActionResult> AnnouncementCreation(AnnouncementModel announcement) // TODO: put in parameter list
        {
            var user = await userManager.GetUserAsync(User);

            AnnouncementRepository ancRepo       = new AnnouncementRepository(configModel.ConnectionString);
            VolunteerRepository    volunteerRepo = new VolunteerRepository(configModel.ConnectionString);
            VolunteerModel         volunteer;

            // Ensure that ONLY staff accounts have access to this API endpoint
            if (user == null || !await userManager.IsInRoleAsync(user, UserHelpers.UserRoles.Staff.ToString()))
            {
                return(Utilities.ErrorJson("Not authorized"));
            }

            // Get the current user's volunteer profile so we can get their name
            volunteer = volunteerRepo.GetVolunteer(user.VolunteerId);

            // Validate the inputs
            // Note that in C#, DateTimes are never null, so instead of checking for null, we check for DateTime.MinValue, which is the
            // default value that ASP.NET's model binding will provide if the date is not included in the API call.
            if (String.IsNullOrEmpty(announcement.Title))
            {
                return(Utilities.ErrorJson("Title field cannot be empty"));
            }
            if (announcement.StartDate == DateTime.MinValue || announcement.EndDate == DateTime.MinValue)
            {
                return(Utilities.ErrorJson("Start and end date must be provided"));
            }
            if (announcement.StartDate > announcement.EndDate)
            {
                return(Utilities.ErrorJson("Start date must be no later than end date"));
            }

            try
            {
                ancRepo.CreateAnnouncement(new AnnouncementModel
                {
                    Title        = announcement.Title,
                    Message      = announcement.Message,
                    Author       = volunteer.FirstName + " " + volunteer.LastName,
                    LastUpdateBy = volunteer.FirstName + " " + volunteer.LastName,
                    StartDate    = announcement.StartDate,
                    EndDate      = announcement.EndDate
                });
            }
            catch (Exception e)
            {
                return(Utilities.ErrorJson(e.Message));
            }


            return(new JsonResult(new
            {
                Error = ""
            }));
        }