Exemplo n.º 1
0
        public ActionResult <SchoolDto> Create(SchoolDto targetValue)
        {
            if (string.IsNullOrWhiteSpace(targetValue.Name))
            {
                return(BadRequest());
            }
            // TODO: there are other rules for validation to consider
            // e.g. we have a limit to the school name length as well as we should ensure that zip code is in the right format
            var result = dataContext.Set <School>().Add(new School
            {
                Name             = targetValue.Name,
                Active           = targetValue.Active,
                SchoolPopulation = targetValue.SchoolPopulation,
                Address          = targetValue.Address == null
                    ? null
                    : new Address
                {
                    AddressLine1 = targetValue.Address.AddressLine1,
                    AddressLine2 = targetValue.Address.AddressLine2,
                    City         = targetValue.Address.City,
                    State        = targetValue.Address.State,
                    Zip          = targetValue.Address.Zip
                }
            });

            dataContext.SaveChanges();
            targetValue.Id = result.Entity.Id;
            return(Created($"/api/schools/{targetValue.Id}", targetValue));
        }
Exemplo n.º 2
0
        public ActionResult Post([FromBody] SchoolDto dto)
        {
            if (string.IsNullOrEmpty(dto.RequesterEmail) || Regex.IsMatch(dto.RequesterEmail, Regexes.Email))
            {
                Problem("The requesterEmail is invalid");
            }

            if (string.IsNullOrEmpty(dto.Url) || Regex.IsMatch(dto.Url, Regexes.Url))
            {
                Problem("The url is invalid");
            }

            var school = new School
            {
                Name        = dto.Name,
                Url         = dto.Url,
                KeeperEmail = dto.RequesterEmail
            };

            school.GenerateId();

            _repository.Create(school);

            return(Ok("Created!"));//TODO: Saturday
        }
Exemplo n.º 3
0
        public HttpResponseMessage Upload()
        {
            HttpPostedFile file = HttpContext.Current.Request.Files["school"];

            ErrMsg         msg    = new ErrMsg();
            IImport        import = ExcelFactory.Instance().GetExcelImporter(new eh.impls.configurations.ExcelConfiguration(1, 0, 0), msg);
            IList <School> list   = SchoolDto.ToList(import.Import <SchoolDto>(file.InputStream));

            if (msg.Count != 0)
            {
                return(ToJson(msg.GetErrors(), status_code: 0, msg: "fail"));
            }
            else
            {
                try
                {
                    Service.Add(list);
                    return(ToJson("success"));
                }
                catch (SqlException ex)
                {
                    msg.AddErrMsg(ex.Message);
                    return(ToJson(msg.GetErrors(), status_code: 0, msg: "fail"));
                }
            }
        }
Exemplo n.º 4
0
        public HttpResponseMessage Post(SchoolDto value)
        {
            var newSchool = new School
            {
                Location = value.Location,
                Name     = value.Name
            };

            HttpResponseMessage response;

            try
            {
                apiControllerHelper.Post <School>(newSchool);

                var createdSchoolDto = new SchoolDto()
                {
                    Id       = newSchool.Id,
                    Name     = newSchool.Name,
                    Location = newSchool.Location
                };

                response = Request.CreateResponse <SchoolDto>(HttpStatusCode.Created, createdSchoolDto);
                var resourceLink = Url.Link("DefaultApi", new { id = createdSchoolDto.Id });

                response.Headers.Location = new Uri(resourceLink);
            }
            catch (Exception ex)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }

            return(response);
        }
        public async Task <IActionResult> UpdateSchool([FromQuery] Guid id, [FromBody] SchoolDto schoolDto)
        {
            try
            {
                if (schoolDto == null)
                {
                    _loggerManager.LogError("SchoolDto object sent from client is null.");
                    return(BadRequest("SchoolDto object is null"));
                }
                if (!ModelState.IsValid)
                {
                    _loggerManager.LogError("Invalid SchoolDto object sent from client.");
                    return(BadRequest("Invalid SchoolDto model object"));
                }
                var dbSchool = await _repositoryWrapper.School.GetSchoolById(id);

                if (dbSchool.IsEmptyObject())
                {
                    _loggerManager.LogError($"School with id: {id}, hasn't been found in db.");
                    return(NotFound());
                }
                var school = _mapper.Map <School>(schoolDto);
                await _repositoryWrapper.School.UpdateSchool(dbSchool, school);

                return(NoContent());
            }
            catch (Exception ex)
            {
                _loggerManager.LogError($"Something went wrong inside UpdateSchool action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
        public async Task <IActionResult> CreateSchool([FromBody] SchoolDto schoolDto)
        {
            try
            {
                if (schoolDto == null)
                {
                    _loggerManager.LogError("SchoolDto object sent from client is null.");
                    return(BadRequest("SchoolDto object is null"));
                }
                if (!ModelState.IsValid)
                {
                    _loggerManager.LogError("Invalid SchoolDto object sent from client.");
                    return(BadRequest("Invalid SchoolDto model object"));
                }
                var school = _mapper.Map <School>(schoolDto);
                await _repositoryWrapper.School.CreateSchool(school);

                if (school.IsEmptyObject())
                {
                    _loggerManager.LogError($"Save operation failed inside CreateSchool action");
                    return(StatusCode(500, "Internal server error while saving School "));
                }
                var dbSchool = await _repositoryWrapper.School.GetSchoolById(school.Id);

                return(Ok(dbSchool));
            }
            catch (Exception ex)
            {
                _loggerManager.LogError($"Something went wrong inside CreateSchool action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 7
0
        public ActionResult <SchoolDto> Update(int id, SchoolDto targetValue)
        {
            var username = User.Identity.Name;
            var isAdmin  = User.IsInRole(Roles.Admin);

            var data = dataContext.Set <School>()
                       .Where(x => isAdmin || x.Staff.Any(y => y.Staff.Users.Any(z => z.UserName == username)))
                       .FirstOrDefault(x => x.Id == id);

            if (data == null)
            {
                return(NotFound());
            }

            // notice the duplication here and in create
            // maybe we can reduce that duplication somehow?
            data.Name             = targetValue.Name;
            data.Active           = targetValue.Active;
            data.SchoolPopulation = targetValue.SchoolPopulation;
            data.Address          = targetValue.Address == null
                ? null
                : new Address
            {
                AddressLine1 = targetValue.Address.AddressLine1,
                AddressLine2 = targetValue.Address.AddressLine2,
                City         = targetValue.Address.City,
                State        = targetValue.Address.State,
                Zip          = targetValue.Address.Zip
            };

            dataContext.SaveChanges();

            return(Ok(targetValue));
        }
Exemplo n.º 8
0
        public async Task <ActionResult <bool> > Update(Guid schoolid, SchoolDto schoolDto)
        {
            try
            {
                var schoolx = await _schoolRepo.GetSchoolWithID(schoolid);

                if (schoolx == null)
                {
                    return(BadRequest($"could not find school with id: {schoolid}"));
                }

                schoolx.schoolid    = schoolDto.schoolid ?? schoolx.schoolid;
                schoolx.name        = schoolDto.name ?? schoolx.name;
                schoolx.address     = schoolDto.address ?? schoolx.address;
                schoolx.phonenumber = schoolDto.phonenumber ?? schoolx.phonenumber;
                schoolx.grade       = schoolDto.grade ?? schoolx.grade;

                var res = await _schoolRepo.SaveAll();

                var schoolxToReturn = _mapper.Map <SchoolDto>(schoolx);

                return(Ok(schoolxToReturn));
            }
            catch (Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException.Message));
            }
        }
Exemplo n.º 9
0
        public async Task LoadAsync(UserEditDto userEditDto)
        {
            _userEditDtoJson = JsonConvert.SerializeObject(userEditDto);
            _userEditDto     = userEditDto;
            _connectedUser   = userEditDto.ConnectedUser;
            _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUser.Token);
            if (_userEditDto.IsNew == null)
            {
                isNewSchool  = true;
                isNewTeacher = true;
            }
            else
            {
                switch (_userEditDto.Type)
                {
                case Shared.Helpers.TypeEnum.School:
                    isNewSchool = false;
                    _school     = await _httpClientService.GetTAsync <School>($"school/getbyIdInclude/{_userEditDto.Entity.Id}");

                    var mediaSchool = _school.Medias.OrderByDescending(x => x.UploadDate).FirstOrDefault();
                    _schoolImagePath = await GetFilePath(_httpClientService, "school", _school, mediaSchool);

                    _schoolProfileImage = _schoolImagePath != null ? new BitmapImage(new Uri(_schoolImagePath)) : null;
                    break;

                case Shared.Helpers.TypeEnum.Teacher:
                    isNewTeacher = false;
                    _teacher     = await _httpClientService.GetTAsync <Teacher>($"teacher/getbyIdInclude/{_userEditDto.Entity.Id}");

                    SelectedSchool = new SchoolDto(_teacher.School);
                    var media = _teacher.Medias.OrderByDescending(x => x.UploadDate).FirstOrDefault();
                    _teacherImagePath = await GetFilePath(_httpClientService, "teacher", _teacher, media);

                    _teacherProfileImage = _teacherImagePath != null ? new BitmapImage(new Uri(_teacherImagePath)) : null;
                    break;

                default:
                    isNewTeacher = true;
                    isNewSchool  = true;
                    break;
                }
                RaisePropertyChanged(nameof(School));
                RaisePropertyChanged(nameof(Teacher));
                RaisePropertyChanged(nameof(SelectedSchool));
                RaisePropertyChanged(nameof(ProfileImageSource));
                RaisePropertyChanged(nameof(TeacherProfileImage));
            }

            var getSchools = await _httpClientService.GetListTAsync <School>("school/getall");

            foreach (var school in getSchools)
            {
                _schools.Add(new SchoolDto(school));
            }
            _teachersList   = getSchools.Select(s => s.Principle).Distinct().ToList();
            _selectTeachers = new ObservableCollection <string>(_teachersList);
            RaisePropertyChanged(nameof(Schools));
            RaisePropertyChanged(nameof(SelectTeachers));
        }
Exemplo n.º 10
0
 private bool validate(SchoolDto request)
 {
     if (request == null)
         return setValidation("No request was found!");
     if (request.Name.IsNullOrEmpty())
         return setValidation("You must enter a department name!");
     return true;
 }
        public async Task <IActionResult> AddNewSchool(SchoolDto body)
        {
            var dto = mapper.Map <SchoolDto, School>(body);

            _unitOfWork.SchoolRepository.AddRecord(dto);
            await _unitOfWork.SaveAsync();

            return(Ok());
        }
Exemplo n.º 12
0
        public async Task <IActionResult> PutSchool(string id, SchoolDto schoolDto)
        {
            var school = _mapper.Map <School>(schoolDto);

            school.Id = id;
            var result = await _schoolService.UpdateSchool(school);

            var response = new ApiResponse <bool>(result);

            return(Ok(response));
        }
Exemplo n.º 13
0
 public ActionResult Edit(SchoolDto school)
 {
     if (ModelState.IsValid)
     {
         var sc = db.Schools.Find(school.Id);
         sc.Name            = school.Name;
         db.Entry(sc).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
 }
Exemplo n.º 14
0
        public async Task <ActionResult <SchoolDto> > GetUserSchool()
        {
            var user = await _userManager.FindByUserByClaimsPrincipleWithSchoolAsync(HttpContext.User);

            var data = _mapper.Map <School, SchoolDto>(user.School);
            var keko = new SchoolDto
            {
                SchoolNameId = user.School.SchoolNameId,
                DinnerTimeId = user.School.DinnerTimeId
            };

            return(Ok(keko));
        }
Exemplo n.º 15
0
        public SchoolDto GetSchool(int id)
        {
            School    school    = lernsiegService.GetSchool(id);
            SchoolDto schoolDto = new SchoolDto
            {
                Id           = school.Id,
                Name         = school.Name,
                Country      = school.Country,
                SchoolNumber = school.SchoolNumber,
                Address      = school.Address,
            };

            return(schoolDto);
        }
Exemplo n.º 16
0
        public static async Task Seed(ISchoolAppDbContext context)
        {
            var entity = new SchoolDto()
            {
                id   = Guid.Parse("eae2acee-5b9c-4f4b-a477-8668fee43fea"),
                name = "Seeded School, For Testing"
            };

            if (context.Schools.Any(x => x.id == entity.id))
            {
                return;
            }
            context.Schools.Add(entity);
            await context.SaveChangesAsync();
        }
Exemplo n.º 17
0
        public IHttpActionResult Add(SchoolDto school)
        {
            try
            {
                var insertedRow = (IDictionary <string, object>)_sqlDA.SaveData <dynamic>("dbo.spSchools_Add",
                                                                                          new { school.City, school.CreationDate, school.Description, school.EmailAddress, school.Name, school.PostalCode, school.Street, school.TelephoneNumber, school.WebAddress });
                insertedRow.TryGetValue("Id", out object insertedId);

                return(Created <string>("", insertedId?.ToString()));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 18
0
        public IHttpActionResult GetSchool(int id)
        {
            School    t      = db.Schools.Find(id);
            SchoolDto school = new SchoolDto()
            {
                Id = t.Id, Address1 = t.Address1, Address2 = t.Address2, Contact = t.ContactNumber, Email = t.Email, Name = t.Name
            };

            if (school == null)
            {
                return(NotFound());
            }

            return(Ok(school));
        }
Exemplo n.º 19
0
        public ActionResult Create(SchoolDto school)
        {
            if (ModelState.IsValid)
            {
                var schoolEntity = new School //object initializer
                {
                    Name = school.Name
                };
                db.Schools.Add(schoolEntity);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
        }
Exemplo n.º 20
0
        public ActionResult Edit(int id)
        {
            School s = db.Schools.Find(id);

            if (s == null)
            {
                return(HttpNotFound());
            }
            var school = new SchoolDto
            {
                Name = s.Name
            };

            return(View(school));
        }
        public async Task <IActionResult> UpdateSchool(string Id, SchoolDto school)
        {
            //Imp
            var querySchoolObj = _unitOfWork.SchoolRepository.GetSingleRecord(Id);

            querySchoolObj.Result.SchCode     = school.SchCode;
            querySchoolObj.Result.SchName     = school.SchName;
            querySchoolObj.Result.SchDeanName = school.SchDeanName;
            querySchoolObj.Result.SchPhone    = school.SchPhone;


            await _unitOfWork.SaveAsync();

            return(Ok(querySchoolObj.Result));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> PostSchool(SchoolDto schoolDto)
        {
            // Console.Write("al api");
            //var school = new School
            //{
            //    Name = schoolDto.Name,
            //    Description = schoolDto.Description,
            //    Logo = schoolDto.Logo,
            //    Status = schoolDto.Status
            //};
            var school = _mapper.Map <School>(schoolDto);
            await _schoolService.InsertSchool(school);

            var response = new ApiResponse <bool>(true);

            return(Ok(response));
        }
        public void CreateSchool()
        {
            // Arrange
            var schoolDto = new SchoolDto
            {
                Name = "New School 1"
            };
            var school = _mapper.Map <School>(schoolDto);

            Mock.Get(_repositoryWrapper.School).Setup(x => x.CreateSchool(school));
            Mock.Get(_repositoryWrapper.School).Setup(x => x.GetSchoolById(school.Id)).ReturnsAsync(school);
            var controller = new SchoolController(_loggerManager, _mapper, _repositoryWrapper);
            // Act
            var actionResult = controller.CreateSchool(schoolDto).Result;
            // Assert
            var okObjectResult = actionResult as OkObjectResult;

            Assert.IsNotNull(okObjectResult);
        }
        public void UpdateSchool()
        {
            // Arrange
            var schoolDto = new SchoolDto
            {
                Name = "Update School 1"
            };
            var school = _mapper.Map <School>(schoolDto);

            school.Id = Guid.NewGuid();
            Mock.Get(_repositoryWrapper.School).Setup(x => x.UpdateSchool(school, school));
            Mock.Get(_repositoryWrapper.School).Setup(x => x.GetSchoolById(school.Id)).ReturnsAsync(school);
            var controller = new SchoolController(_loggerManager, _mapper, _repositoryWrapper);
            // Act
            var actionResult = controller.UpdateSchool(school.Id, schoolDto).Result;
            // Assert
            var noContentResult = actionResult as NoContentResult;

            Assert.IsNotNull(noContentResult);
        }
Exemplo n.º 25
0
        public async Task <IActionResult> PutSchools(int id, SchoolDto schoolDto)
        {
            if (schoolDto.Id == 0)
            {
                schoolDto.Id = id;
            }
            if (id != schoolDto.Id)
            {
                return(BadRequest());
            }

            var school = await _context.Schools.FirstOrDefaultAsync(_ => _.Id == schoolDto.Id);

            if (school == null)
            {
                return(NotFound());
            }
            if (schoolDto.Name != null)
            {
                school.Name = schoolDto.Name;
            }
            if (schoolDto.Display != null)
            {
                school.Display = schoolDto.Display.Value;
            }
            school.DateModified          = DateTime.Now;
            _context.Entry(school).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

            return(RedirectToAction("GetSchools", new { id = schoolDto.Id }));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> PostSchools(SchoolDto schoolDto)
        {
            if (schoolDto.Id == 0)
            {
                if (schoolDto.Name == null)
                {
                    return(BadRequest());
                }
                if (schoolDto.Display == null)
                {
                    schoolDto.Display = true;
                }
                var school = _mapper.Map <School>(schoolDto);
                _context.Schools.Add(school);
                await _context.SaveChangesAsync();

                return(CreatedAtAction("GetSchools", new { id = school.Id }, _mapper.Map <SchoolDto>(school)));
            }
            else
            {
                return(await PutSchools(schoolDto.Id, schoolDto));
            }
        }
Exemplo n.º 27
0
        public IActionResult Put_Schools(int key, [FromBody] SchoolDto update)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (key != update.Id)
            {
                return(BadRequest());
            }

            var school = _db.Schools.AsTracking()
                         .Include(x => x.Students).SingleOrDefault(x => x.Id == key);

            //_db.Schools.AsTracking()
            //.Include(x => x.Registry).SingleOrDefault(x => x.Id == key);

            _db.Schools.Persist().InsertOrUpdate(update);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_SchoolsExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(school));
        }
Exemplo n.º 28
0
        public async Task <IActionResult> GetSchools()
        {
            var schools = await _studentService.GetSchools();

            return(Ok(SchoolDto.Map(schools)));
        }
Exemplo n.º 29
0
 public SchoolDto Add(SchoolDto subject)
 {
     return(schoolStorage.Add(subject));
 }
Exemplo n.º 30
0
 public void Update(SchoolDto subject)
 {
     schoolStorage.Update(subject);
 }
Exemplo n.º 31
0
 public Task <SchoolDto> Update(SchoolDto entity)
 {
     throw new NotImplementedException();
 }