예제 #1
0
        public async Task <IActionResult> CreateMovieRole(MovieRole movieRole)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (await appRepository.GetMovieRoleByParams(movieRole.MovieId, movieRole.ArtistId, movieRole.RoleTypeId) != null ||
                await appRepository.GetMovieRoleByParams(movieRole.MovieId, movieRole.ArtistId, movieRole.RoleTypeId, userId) != null)
            {
                return(BadRequest("The movie role already exists"));
            }
            var artist = await appRepository.GetArtist(movieRole.ArtistId);

            if (artist == null)
            {
                artist = await appRepository.GetArtist(movieRole.ArtistId, userId);
            }
            if (artist == null)
            {
                return(BadRequest("The artist does not exist"));
            }
            movieRole.Artist           = artist;
            movieRole.IsArtistApproved = artist.IsApproved;
            var movie = await appRepository.GetMovie(movieRole.MovieId);

            if (movie == null)
            {
                movie = await appRepository.GetMovie(movieRole.MovieId, userId);
            }
            if (movie == null)
            {
                return(BadRequest("The movie does not exist"));
            }
            movieRole.Movie           = movie;
            movieRole.IsMovieApproved = movie.IsApproved;
            var roleType = await appRepository.GetRoleType(movieRole.RoleTypeId);

            if (roleType == null)
            {
                return(BadRequest("The role type does not exist"));
            }
            appRepository.Add(movieRole);
            if (await appRepository.SaveAll())
            {
                var activity = new MovieRoleActivityLog();
                activity.RoleDescription = movieRole.RoleDescription;
                activity.AddedByUserId   = userId;
                activity.MovieRoleId     = movieRole.Id;
                appRepository.Add(activity);
                if (await appRepository.SaveAll())
                {
                    return(CreatedAtRoute("GetMovieRole", new { id = movieRole.Id }, movieRole));
                }
                return(BadRequest("Unable to Add Movie Role"));
            }
            return(BadRequest("Unable to Add Movie Role"));
        }
예제 #2
0
        public async Task <IActionResult> AddGroup([FromForm] GroupModel model)
        {
            try
            {
                if (this.ValidRoleForAction(_context, _auth, new string[] { "Editor" }))
                {
                    if (ModelState.IsValid)
                    {
                        PhotoUploadCloudinary upload = new PhotoUploadCloudinary(_cloudinaryConfig);
                        Photo photo = upload.Upload(model.Photo);

                        Group item = new Group
                        {
                            Name            = model.Name,
                            FacultyId       = model.FacultyId,
                            LessonEndDate   = model.LessonEndDate,
                            LessonStartDate = model.LessonStartDate,
                            LessonHourId    = model.LessonHourId,
                            LessonStatusId  = 1,
                            Photo           = photo,
                            RoomId          = model.RoomId
                        };

                        Teacher teacher = await _context.GetByIdAsync <Teacher>(x => x.Id == model.TeacherId);

                        if (teacher != null)
                        {
                            TeacherGroup teacherGroup = new TeacherGroup {
                                Group = item, Teacher = teacher
                            };
                            await _context.Add(teacherGroup);
                        }
                        await _context.Add(item);

                        if (await _context.SaveAll())
                        {
                            return(Ok(item));
                        }
                    }
                    return(BadRequest("Model is not valid"));
                }
                return(Forbid());
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _auth);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
예제 #3
0
        public async Task <IActionResult> AddArtistPhoto(int artistId, [FromForm] PhotoForUploadDTO photoForUploadDTO)
        {
            var artist = await appRepository.GetArtist(artistId);

            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (artist == null)
            {
                artist = await appRepository.GetArtist(artistId, userId);
            }
            if (artist == null)
            {
                return(BadRequest("Artist does not exist"));
            }
            if (photoForUploadDTO.File.Length > 10 * 1024 * 1024)
            {
                return(BadRequest("Max file size should be 10 MB."));
            }
            using (var stream = photoForUploadDTO.File.OpenReadStream())
            {
                if (!IsImage(stream))
                {
                    return(BadRequest("The file " + photoForUploadDTO.File.FileName + " is not an image!"));
                }
            }
            var photo = await UploadPhoto(photoForUploadDTO.File);

            if (photo == null)
            {
                return(BadRequest("Unable to upload photo"));
            }
            var artistPhoto = new ArtistPhoto();

            if (artist.IsApproved)
            {
                artistPhoto.IsArtistApproved = true;
            }
            artistPhoto.Artist   = artist;
            artistPhoto.ArtistId = artist.Id;
            artistPhoto.Photo    = photo;
            artistPhoto.PhotoId  = photo.Id;
            appRepository.Add(artistPhoto);
            if (await appRepository.SaveAll())
            {
                return(CreatedAtRoute("GetArtistPhoto", new{ artistId = artist.Id, photoId = photo.Id }, artistPhoto));
            }
            return(BadRequest("Unable to add photo"));
        }
예제 #4
0
        public bool UpdateSysPreferences(SysPrefsModel updateSysPrefsModel)
        {
            bool updated = false;

            if (updateSysPrefsModel.SysPrefs.SysPrefsId > 0)
            {
                // it means that there was a record in the database.
                var recsUpdated = _SysPrefsRepo.Update(updateSysPrefsModel.SysPrefs);
                updated = (recsUpdated == 1);
            }
            else
            {
                // it means that there was a record in the database.
                var recIsUpdated = _SysPrefsRepo.Add(updateSysPrefsModel.SysPrefs) > 0;
                updated = recIsUpdated;
            }
            // run this update regardless
            if (updateSysPrefsModel.WooSettings.WooSettingsId > 0)
            {
                // it means that there was a record in the database.
                var recsUpdated = _WooSettingsRepo.Update(updateSysPrefsModel.WooSettings);
                updated = updated && (recsUpdated == 1);
            }
            else
            {
                // it means that there was a record in the database.
                var recIsUpdated = _WooSettingsRepo.Add(updateSysPrefsModel.WooSettings) > 0;
                updated = updated && recIsUpdated;
            }
            return(updated);
        }
예제 #5
0
        public ActionResult AddCity([FromBody] City city)
        {
            _repository.Add(city);
            _repository.SaveAll();

            return(Ok(city));
        }
예제 #6
0
        public Task <bool> Handle(RegistrarNovoAppCommand message, CancellationToken cancellationToken)
        {
            #region Basic Validation
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }
            #endregion

            #region Others Validations
            if (_appRepository.ObterPorNome(message.ClienteId, message.Nome) != null)
            {
                _bus.RaiseEvent(new DomainNotification(message.MessageType, "Já existe um app com este nome"));
            }
            #endregion

            var app = new App(message.Id, message.TipoAppId, message.ClienteId, message.Nome, message.DataCadastro, message.Descrição);

            _appRepository.Add(app);

            if (Commit())
            {
                _bus.RaiseEvent(new RegistrarNovoAppEvent());
            }

            return(Task.FromResult(true));
        }
        public IActionResult AddRecourse([FromBody] RecourseRequest req)
        {
            string profilePictureUrl = null;

            string result = Regex.Replace(req.url, "^data:image/[a-zA-Z]+;base64,", string.Empty);

            if (req.url != null)
            {
                profilePictureUrl = $"images/{req.studentId.ToString()}_{Guid.NewGuid().ToString()}.jpg";
                var profilePictureFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", profilePictureUrl);
                System.IO.File.WriteAllBytes(profilePictureFilePath, Convert.FromBase64String(result));
            }

            if (profilePictureUrl != null)
            {
                var addRecourse = new Recourse()
                {
                    studentId  = req.studentId,
                    isApproved = 0,
                    url        = profilePictureUrl,
                    date       = DateTime.Now
                };
                _appRepository.Add(addRecourse);
                return(Ok(_appRepository.SaveAll()));
            }

            return(StatusCode(400));
        }
        public ActionResult CompanyAdd([FromBody] CompanyRequest company)
        {
            string profilePictureUrl = null;

            string result = Regex.Replace(company.logoUrl, "^data:image/[a-zA-Z]+;base64,", string.Empty);

            if (company.logoUrl != null)
            {
                profilePictureUrl = $"images/{company.name}_{Guid.NewGuid().ToString()}.jpg";
                var profilePictureFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", profilePictureUrl);
                System.IO.File.WriteAllBytes(profilePictureFilePath, Convert.FromBase64String(result));
            }

            var createCompany = new Company()
            {
                personelCount = company.personelCount,
                telephone     = company.telephone,
                address       = company.address,
                logoUrl       = profilePictureUrl,
                mail          = company.mail,
                name          = company.name
            };

            _appRepository.Add(createCompany);
            _appRepository.SaveAll();
            _appRepository.setCompanyId(company.userId, createCompany.id);
            _appRepository.SaveAll();
            return(Ok(createCompany));
        }
예제 #9
0
            public async Task <HomeDto> Handle(Command request, CancellationToken cancellationToken)
            {
                if ((await _appRepo.Search(x => x.Name.ToUpper() == request.Name.ToUpper())) != null)
                {
                    throw new RestException(HttpStatusCode.BadRequest, new  { Name = "Care Home exists." });
                }

                var newHomeDto = new HomeDto()
                {
                    Name    = request.Name,
                    City    = request.City,
                    Address = request.Address,
                    Email   = request.Email,
                    Rating  = request.Rating
                };

                _appRepo.Add(_mapper.Map <Homes>(newHomeDto));

                if (await _appRepo.SaveAllAsync())
                {
                    return(newHomeDto);
                }

                throw new Exception("Problem saving new Care Home");
            }
 public ActionResult Add([FromBody] City city)
 {
     //test
     _appRepository.Add(city);
     _appRepository.SaveAll();
     return(Ok(city));
 }
예제 #11
0
        public async Task <IActionResult> CreateMessage(int userId, MessageForCreationDto messageForCreationDto)
        {
            var sender = await _repo.GetUser(userId);

            if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            messageForCreationDto.SenderId = userId;

            var recipient = await _repo.GetUser(messageForCreationDto.RecipientId);

            if (recipient == null)
            {
                return(BadRequest("Could not find user"));
            }

            var message = _mapper.Map <Message1>(messageForCreationDto);

            _repo.Add(message);

            if (await _repo.SaveAll())
            {
                var messageToReturn = _mapper.Map <MessageToReturnDto>(message);
                return(CreatedAtRoute("GetMessage",
                                      new { userId, id = message.Id }, messageToReturn));
            }

            throw new Exception("Creating the message failed on save");
        }
예제 #12
0
        public async Task <IActionResult> CreateGroup([FromBody] GroupForCreateDto groupForCreateDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var groupToCreate = new Grupo
            {
                Cidade             = groupForCreateDto.Cidade,
                Estado             = groupForCreateDto.Estado,
                CodigoUsuarioLider = groupForCreateDto.CodigoUsuarioLider,
                Descricao          = groupForCreateDto.Descricao,
                Nivel = groupForCreateDto.Nivel,
                Nome  = groupForCreateDto.Nome,
                QuantidadeMembrosAtual  = groupForCreateDto.QuantidadeMembrosAtual,
                QuantidadeMembrosMaxima = groupForCreateDto.QuantidadeMembrosMaxima,
                Fotos = groupForCreateDto.Fotos
            };

            _repo.Add <Grupo>(groupToCreate);

            if (await _repo.SaveAll())
            {
                return(StatusCode(201));
            }

            return(BadRequest("Falha ao criar grupo"));
        }
예제 #13
0
        public async Task <IActionResult> LikeUser(int id, int recipientId)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var like = await _repo.GetLike(id, recipientId);

            if (like != null)
            {
                return(BadRequest("You already like this user"));
            }

            if (await _repo.GetUser(recipientId) == null)
            {
                return(NotFound());
            }

            like = new Like
            {
                LikerId = id,
                LikeeId = recipientId
            };

            _repo.Add <Like>(like);

            if (await _repo.SaveAll())
            {
                return(Ok());
            }

            return(BadRequest("Failed to like user"));
        }
예제 #14
0
        public async Task <IActionResult> Add([FromForm] LessonStatusModel model)
        {
            try
            {
                if (this.ValidRoleForAction(_context, _auth, new string[] { "Admin" }))
                {
                    bool saved;
                    if (ModelState.IsValid)
                    {
                        LessonStatus item = new LessonStatus
                        {
                            Name = model.Name,
                        };

                        await _context.Add(item);

                        saved = await _context.SaveAll();

                        if (saved == true)
                        {
                            return(Ok(item));
                        }
                    }
                    return(BadRequest("Model is not valid"));
                }
                return(Forbid());
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _auth);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
예제 #15
0
        public ActionResult Add([FromBody] City city)
        {
            _appRepository.Add(city);

            //Unit of Work Desing Pattern
            _appRepository.SaveAll();

            return(Ok(city));
        }
예제 #16
0
 public async Task <IActionResult> CreateRoleType(RoleType roleType)
 {
     appRepository.Add(roleType);
     if (await appRepository.SaveAll())
     {
         return(CreatedAtRoute("GetRoleType", new { id = roleType.Id }, roleType));
     }
     return(BadRequest("Unable to Add Role Type"));
 }
예제 #17
0
        private async Task AddGitHubAppsNotInRepository()
        {
            App[] newGitHubApps = _gitHubAppsByName.Values.Where(app => !_repositoryAppsByName.ContainsKey(app.Name)).ToArray();

            foreach (App app in newGitHubApps)
            {
                await _appRepository.Add(app);
            }
        }
예제 #18
0
 public async Task <IActionResult> CreateOrder(Order orderToCreate)
 {
     _appRepo.Add(orderToCreate);
     if (await _appRepo.SaveAll())
     {
         return(Ok("Order succsessfully created"));
     }
     return(BadRequest("Problem creating order"));
 }
예제 #19
0
 public async Task <IActionResult> AddTool(Tool toolToCreate)
 {
     _appRepo.Add(toolToCreate);
     if (await _appRepo.SaveAll())
     {
         return(Ok("Tool succsessfully added"));
     }
     return(BadRequest("Problem adding tool"));
 }
예제 #20
0
        public async Task <IActionResult> AddWorkLog(InsertWorkLogDto workLogDto)
        {
            var WorkLog = _mapper.Map <Model.WorkLog>(workLogDto);

            _repo.Add(WorkLog);
            var result = await _repo.SaveAll();

            return(Ok(result));
        }
예제 #21
0
        public async Task <IActionResult> Register([FromBody] MusteriRegisterDto musteriRegisterDto)
        {
            if (await _authRepository.UserExists(musteriRegisterDto.TCKN))
            {
                ModelState.AddModelError("UserExist", "Username already exists");
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            int myRandomNo;

            while (true)
            {
                Random rnd = new Random();
                myRandomNo = rnd.Next(10000000, 99999999);
                if (!UniqueHesapNo(myRandomNo.ToString()))
                {
                    break;
                }
            }
            Musteri musteri = new Musteri
            {
                Ad     = musteriRegisterDto.Ad,
                Soyad  = musteriRegisterDto.Soyad,
                TCKN   = musteriRegisterDto.TCKN,
                Sifre  = musteriRegisterDto.Sifre,
                Adres  = musteriRegisterDto.Adres,
                EPosta = musteriRegisterDto.EPosta,
                TelNo  = musteriRegisterDto.TelNo,
            };
            var remusteri = await _authRepository.Register(musteri);

            if (remusteri == null)
            {
                return(BadRequest(ModelState));
            }
            Hesap hesap = new Hesap
            {
                AktiflikDurumu = true,
                BakiyeBilgi    = 0,
                EkNo           = 1000,
                HesapNo        = myRandomNo.ToString(),
                Musteri        = musteri,
                TCKN           = musteri.TCKN
            };

            _appRepository.Add(hesap);

            if (!_appRepository.SaveAll())
            {
                return(BadRequest(ModelState));
            }

            return(StatusCode(201));
        }
예제 #22
0
        public async Task <IActionResult> CreateMovie(Movie movie)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            appRepository.Add(movie);
            if (await appRepository.SaveAll())
            {
                var activity = mapper.Map <MovieActivityLog>(movie);
                activity.MovieId       = movie.Id;
                activity.AddedByUserId = userId;
                appRepository.Add(activity);
                if (await appRepository.SaveAll())
                {
                    return(CreatedAtRoute("GetMovie", new { id = movie.Id }, movie));
                }
                return(BadRequest("Unable to Add Movie"));
            }
            return(BadRequest("Unable to Add Movie"));
        }
예제 #23
0
        public void Add(App model)
        {
            var entity = AppFactory.Create(model);

            _appFileRepository.Add(entity.File);
            model.File.Id = entity.Id;

            _appRepository.Add(entity);
            model.Id = entity.Id;
        }
예제 #24
0
        public async Task <IActionResult> AddProduct(ProductToAddDto productToAddDto)
        {
            var warehouse = await _warehouserepo.GetWarehouse(productToAddDto.WarehouseId);

            if (warehouse == null)
            {
                return(BadRequest("No warehouse by this Id"));
            }

            if (!await _warehouserepo.ZoneExists(warehouse.WarehouseId, productToAddDto.ZoneId))
            {
                return(BadRequest("Provided zone does not exist in this warehouse"));
            }
            //здесь добавить проверку на то, осталось ли достаточно места на складе.
            //Если да - вернуть зону, в котрую пометсить продукт


            var user = await _authrepo.GetUser(productToAddDto.Username, UserTypes.Renter);

            if (user == null)
            {
                return(BadRequest("User does not exist"));
            }

            var productToCreate = _mapper.Map <Product>(productToAddDto);

            productToCreate.UserId = user.UserId;

            _apprepo.Add(productToCreate);
            if (!await _apprepo.SaveAll())
            {
                return(BadRequest("Problem adding product"));
            }

            ProductInWarehouse piw = new ProductInWarehouse(warehouse.WarehouseId, productToCreate.ProductId, productToAddDto.ZoneId);

            _apprepo.Add(piw);
            if (await _apprepo.SaveAll())
            {
                return(Ok(piw));
            }
            return(BadRequest("Problem adding product"));
        }
예제 #25
0
        public async Task <IActionResult> CreateArtist(Artist artist)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            appRepository.Add(artist);
            if (await appRepository.SaveAll())
            {
                var activity = mapper.Map <ArtistActivityLog>(artist);
                activity.ArtistId      = artist.Id;
                activity.AddedByUserId = userId;
                appRepository.Add(activity);
                if (await appRepository.SaveAll())
                {
                    return(CreatedAtRoute("GetArtist", new { id = artist.Id }, artist));
                }
                return(BadRequest("Unable to Add Artist"));
            }
            return(BadRequest("Unable to Add Artist"));
        }
예제 #26
0
        public async Task <IActionResult> AddQualification(QualDto qualDto)
        {
            var qual = _mapper.Map <Qualification>(qualDto);

            _appRepository.Add(qual);

            await _unitOfWork.SaveAll();

            return(Ok(qual));
        }
        public async Task <IActionResult> Add([FromForm] LeftNavItemModel model)
        {
            try
            {
                if (this.ValidRoleForAction(_context, _auth, new string[] { "Admin" }))
                {
                    bool saved;
                    if (ModelState.IsValid)
                    {
                        PhotoUploadCloudinary upload = new PhotoUploadCloudinary(_cloudinaryConfig);
                        Photo photo = upload.Upload(model.Photo);

                        LeftNavItem item = new LeftNavItem
                        {
                            Name          = model.Name,
                            RouterLink    = model.RouterLink,
                            IconClassname = model.IconClassname,
                            IsVisible     = model.IsVisible,
                            Photo         = photo
                        };

                        await _context.Add(photo);

                        await _context.Add(item);

                        saved = await _context.SaveAll();

                        if (saved == true)
                        {
                            return(Ok(item));
                        }
                    }
                    return(BadRequest("Model is not valid"));
                }
                return(Forbid());
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _auth);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
예제 #28
0
        public async Task <IActionResult> AddStaff(StaffDto staffDto)
        {
            var staff = _mapper.Map <Staff>(staffDto);

            _appRepository.Add(staff);

            await _unitOfWork.SaveAll();

            return(Ok(staff));
        }
예제 #29
0
        public async Task <IActionResult> CreateEmpoyee(EmployeeToCreateDto EmployeeToCreate)
        {
            var EmployeeToCreateRepo = _mapper.Map <Model.Employee>(EmployeeToCreate);


            _repo.Add(EmployeeToCreateRepo);
            var result = await _repo.SaveAll();

            return(Ok(result));
        }
예제 #30
0
        public ActionResult Add_Work([FromBody] Work work)
        {
            work.userId       = 2;// TODO: İşlevsellik sağlanacak
            work.terminDate   = Utils.GetTerminDate(work.coefficient);
            work.finishStatus = (int)helperEnum.finishStatus.notStart;
            work.workStatus   = (int)helperEnum.workStatus.notStart;

            _appRepository.Add(work);
            _appRepository.SaveAll();
            return(Ok(work));
        }