public async Task <ServiceResult <MedicalRecordModel> > RemoveAsync(int id) { var entity = await _db.MedicalRecords.FirstOrDefaultAsync(x => x.Id == id); if (entity == null) { return(ServiceResult <MedicalRecordModel> .Fail("MedicalRecord not found")); } try { _db.MedicalRecords.Remove(entity); await _db.SaveChangesAsync(); return(ServiceResult <MedicalRecordModel> .Success(new MedicalRecordModel { Id = entity.Id, MedicalRecordUrl = entity.MedicalRecordUrl, AnimalId = entity.AnimalId })); } catch (Exception ex) { //todo: log error return(ServiceResult <MedicalRecordModel> .Fail("Internal server error")); } }
public async Task <ServiceResult <FacultyDto> > CreateFacultyAsync(FacultyAddRequest request) { if (!await _unitOfWork.UniversityRepository.IsExistById(request.UniversityId)) { return(ServiceResult <FacultyDto> .Fail(EOperationResult.EntityNotFound, "University with this Id doesn't exist")); } var newFaculty = new Faculty() { FullTitle = request.FullTitle, ShortTitle = request.ShortTitle, Description = request.Description, UniversityId = request.UniversityId, Avatar = request.Avatar }; if (string.IsNullOrEmpty(newFaculty.Avatar)) { newFaculty.Avatar = _urlOptions.ServerUrl + DefaultImagesConstants.DefaultImage; } _unitOfWork.FacultyRepository.Add(newFaculty); await _unitOfWork.CommitAsync(); return(ServiceResult <FacultyDto> .Ok(_mapper.Map <Faculty, FacultyDto>(newFaculty))); }
public async Task <ServiceResult <UserDto> > UpdateUsersInfoAsync(int userId, UpdateUserInfoRequest request) { User user = await _unitOfWork.UserRepository.GetSingleAsync(up => up.Id == userId); if (user == null) { return(ServiceResult <UserDto> .Fail(EOperationResult.EntityNotFound, "User doesn't exist")); } if (!string.IsNullOrEmpty(request.NewUsername)) { if (await _unitOfWork.UserRepository.AnyAsync(u => u.Username == request.NewUsername)) { return(ServiceResult <UserDto> .Fail(EOperationResult.ValidationError, "User with this username already exist")); } user.Username = request.NewUsername; } if (!string.IsNullOrEmpty(request.NewAvatar)) { user.Avatar = request.NewAvatar; } await _unitOfWork.CommitAsync(); return(ServiceResult <UserDto> .Ok(_mapper.Map <User, UserDto>(user))); }
public async Task <ServiceResult <EditMedicalRecordModel> > EditAsync(EditMedicalRecordModel model) { var entity = await _db.MedicalRecords.FirstOrDefaultAsync(x => x.Id == model.Id); if (entity == null) { return(ServiceResult <EditMedicalRecordModel> .Fail("MedicalRecord not found")); } entity.AnimalId = model.AnimalId; entity.MedicalRecordUrl = model.MedicalRecordUrl; try { await _db.SaveChangesAsync(); return(ServiceResult <EditMedicalRecordModel> .Success(new EditMedicalRecordModel { Id = entity.Id, AnimalId = entity.AnimalId, MedicalRecordUrl = entity.MedicalRecordUrl })); } catch (Exception ex) { //log error return(ServiceResult <EditMedicalRecordModel> .Fail("Internal server error")); } }
/// <summary> /// دریافت آدرس اصلی از آدرس کوتاه /// </summary> /// <param name="shortAddress"></param> /// <param name="visitorIpAddress"></param> /// <returns></returns> public ServiceResult <string> GetFullAddressByShortLink(string shortAddress, string visitorIpAddress) { ///اقدام به اعتبار سنجی آدرس اصلی var shortAddressValidationResult = ShortAddressValidation(shortAddress); if (shortAddressValidationResult.IsFailure) { return(ServiceResult <string> .Fail(message : shortAddressValidationResult.Message)); } ///اقدام به دریافت لینک به وسیله آدرس کوتاه Link link = linkQueryRepository.GetByShortAddress(shortAddress); if (link == null) { return(ServiceResult <string> .Fail("برای لینک کوتاه شده لینک کاملی یافت نشد")); } ///اقدام به ایجاد لینکویزیت جدید در دیتابیس LinkVisit linkVisit = LinkVisitGenerator(link.Id, visitorIpAddress); var result = linkVisitCommandRepository.Add(linkVisit); if (!result) { return(ServiceResult <string> .Fail("خطا در ثبت آمار")); } ///ارسال نتیجه return(ServiceResult <string> .Ok(value : link.FullAddress.Value)); }
public async Task <ServiceResult <string> > UploadImageAsync(IFormFile imageFile) { string extension = Path.HasExtension(imageFile.FileName) ? Path.GetExtension(imageFile.FileName) : string.Empty; if (!_imageExtensions.Contains(extension)) { return(ServiceResult <string> .Fail(EOperationResult.ValidationError, "Invalid extension")); } string fileName = $"image_{Guid.NewGuid()} + {extension}"; string relativeFilePath = Path.Combine(_fileOptions.UploadFolder, _fileOptions.InnerFolders.ImagesFolder, fileName); string fullPath = Path.Combine(_hostingEnvironment.ContentRootPath, relativeFilePath); if (imageFile.Length > _fileSize) { CompressImageAndWriteImageToFile(fullPath, imageFile); } else { using (var fileStream = new FileStream(fullPath, FileMode.Create)) { await imageFile.CopyToAsync(fileStream); } } string urlPath = Path.Combine(_urlOptions.ServerUrl, relativeFilePath); return(ServiceResult <string> .Ok(urlPath)); }
public async Task <ServiceResult <AnimalModel> > RemoveAsync(int id) { var entity = await _db.Animals.Include(x => x.MedicalRecords).FirstOrDefaultAsync(x => x.Id == id); if (entity == null) { return(ServiceResult <AnimalModel> .Fail("Animal not found")); } try { _db.MedicalRecords.RemoveRange(entity.MedicalRecords); _db.Animals.Remove(entity); await _db.SaveChangesAsync(); return(ServiceResult <AnimalModel> .Success(new AnimalModel { Id = entity.Id, Name = entity.Name, PasswordNo = entity.PasswordNo, ImageUrl = entity.ImageUrl })); } catch (Exception ex) { //todo: log error return(ServiceResult <AnimalModel> .Fail("Internal server error")); } }
public async Task <ServiceResult <TokenModel> > UpdateTokenAsync(RefreshTokenRequest refreshToken) { var oldRefreshToken = (await _unitOfWork.RefreshTokenRepository.GetSingleAsync( r => r.Token == refreshToken.RefreshToken, r => r.User)); if (oldRefreshToken?.User == null) { return(ServiceResult <TokenModel> .Fail(EOperationResult.ValidationError, "Refresh token is invalid")); } var isRefreshTokenValid = await _refreshTokenService.IsValidRefreshTokenAsync(refreshToken.RefreshToken); if (!isRefreshTokenValid) { return(ServiceResult <TokenModel> .Fail(EOperationResult.ValidationError, "Refresh token is invalid")); } var keyValueList = new List <KeyValuePair <object, object> > { new KeyValuePair <object, object>(SetOfKeysForClaims.UserId, oldRefreshToken.User.Id) }; return(ServiceResult <TokenModel> .Ok( await _refreshTokenService.GetTokenModelAsync(keyValueList, oldRefreshToken.UserId, refreshToken.RefreshToken))); }
public async Task <ServiceResult <CityDto> > CreateCityAsync(CityAddRequest request) { if (!await _unitOfWork.CountryRepository.IsExistById(request.CountryId)) { return(ServiceResult <CityDto> .Fail(EOperationResult.EntityNotFound, "Country with this Id doesn't exist")); } if (await _unitOfWork.CityRepository.IsCityExistAsync(request.Title, request.CountryId)) { return(ServiceResult <CityDto> .Fail(EOperationResult.AlreadyExist, "City with this title already exist in this country")); } var newCity = new City() { Title = request.Title, CountryId = request.CountryId }; _unitOfWork.CityRepository.Add(newCity); await _unitOfWork.CommitAsync(); return(ServiceResult <CityDto> .Ok(_mapper.Map <City, CityDto>(newCity))); }
public async Task <ServiceResult <IEnumerable <BookSearchItem> > > SearchByTitleAsync(string title) { try { var tasks = _bookSearchDataProviders .Select(x => x.SearchByTitleAsync(title)); var searchResults = await Task.WhenAll(tasks); var searchItems = searchResults .SelectMany(x => x) .GroupBy(x => x.Isbn?.Id10Digits, (id, items) => { var itemsList = items.ToList(); return(new BookSearchItem { Isbn = id, Title = itemsList.First().Title, Authors = itemsList.First().Authors, Providers = itemsList.Select(p => p.Provider) }); }) .ToList(); return(ServiceResult <IEnumerable <BookSearchItem> > .Success(searchItems)); } catch (Exception e) { var msg = $"Search by title ({title}) failed."; _logger.LogError(e, msg); return(ServiceResult <IEnumerable <BookSearchItem> > .Fail(msg)); } }
/// <summary> /// دریافت جزئیات لینک /// </summary> /// <param name="shortAddress"></param> /// <returns></returns> public ServiceResult <LinkDetailDto> GetLinkDetailDtoByShortLink(string shortAddress) { ///اقدام به اعتبار سنجی آدرس اصلی var shortAddressValidationResult = ShortAddressValidation(shortAddress); if (shortAddressValidationResult.IsFailure) { return(ServiceResult <LinkDetailDto> .Fail(message : shortAddressValidationResult.Message)); } ///اقدام به دریافت لینک به وسیله آدرس کوتاه Link link = linkQueryRepository.GetByShortAddress(shortAddress); if (link == null) { return(ServiceResult <LinkDetailDto> .Fail("برای لینک کوتاه شده لینک کاملی یافت نشد")); } ///دریافت آمار بازدید به وسیلع شناسه لینک int totalVisitCount = linkVisitQueryRepository.GetTotalVisitCountByLinkId(link.Id); ///ارسال نتیجه LinkDetailDto dto = new LinkDetailDto(link.FullAddress.Value, link.ShortAddress.Value, totalVisitCount); return(ServiceResult <LinkDetailDto> .Ok(value : dto)); }
public async Task <ServiceResult <UserDto> > UpdatePasswordAsync(int userId, UpdatePasswordRequest request) { User user = await _unitOfWork.UserRepository.GetSingleAsync(up => up.Id == userId); if (user == null) { return(ServiceResult <UserDto> .Fail(EOperationResult.EntityNotFound, "User doesn't exist")); } if (!string.IsNullOrEmpty(request.NewPassword)) { if (!Authenticate.Verify(request.CurrentPassword, user.PasswordHash)) { return(ServiceResult <UserDto> .Fail(EOperationResult.ValidationError, "Current password is incorrect")); } user.PasswordHash = Authenticate.Hash(request.NewPassword); } await _unitOfWork.CommitAsync(); return(ServiceResult <UserDto> .Ok(_mapper.Map <User, UserDto>(user))); }
private async Task <ServiceResult <PostLongDto> > PerformVoteRequestValidationAsync(Post post, int userId, ERoleType userRole, PostVote existingVote, EPostVoteType newPostVoteType) { ServiceResult <PostLongDto> validationResult = null; if (post == null) { validationResult = ServiceResult <PostLongDto> .Fail(EOperationResult.EntityNotFound, "Post not found"); } var isUserUnlockedPost = await _unitOfWork.UserAvailablePostRepository.AnyAsync(up => up.UserId == userId && up.PostId == post.Id); if (!isUserUnlockedPost && userRole != ERoleType.Admin) { validationResult = ServiceResult <PostLongDto> .Fail(EOperationResult.ValidationError, "You need to unlock the post before voting"); } if (existingVote?.VoteTypeId == (int)newPostVoteType) { validationResult = ServiceResult <PostLongDto> .Fail(EOperationResult.AlreadyExist, "You already voted on this post"); } return(validationResult ?? (validationResult = ServiceResult <PostLongDto> .Ok())); }
public async Task <ServiceResult <EditMedicalRecordModel> > AddAsync(EditMedicalRecordModel model) { var entity = new MedicalRecord { MedicalRecordUrl = model.MedicalRecordUrl, AnimalId = model.AnimalId }; _db.Add(entity); try { await _db.SaveChangesAsync(); return(ServiceResult <EditMedicalRecordModel> .Success(new EditMedicalRecordModel { Id = entity.Id, MedicalRecordUrl = model.MedicalRecordUrl, AnimalId = model.AnimalId })); } catch (Exception ex) { //log error return(ServiceResult <EditMedicalRecordModel> .Fail("Internal server error")); } }
public async Task <ServiceResult <EditAnimalModel> > EditAsync(EditAnimalModel model) { var entity = await _db.Animals.FirstOrDefaultAsync(x => x.Id == model.Id); if (entity == null) { return(ServiceResult <EditAnimalModel> .Fail("Animal not found")); } entity.Name = model.Name; entity.PasswordNo = model.PasswordNo; entity.ImageUrl = model.ImageUrl; try { await _db.SaveChangesAsync(); return(ServiceResult <EditAnimalModel> .Success(new EditAnimalModel { Id = entity.Id, PasswordNo = entity.PasswordNo, ImageUrl = entity.ImageUrl })); } catch (Exception ex) { //log error return(ServiceResult <EditAnimalModel> .Fail("Internal server error")); } }
public async Task <ServiceResult <PostLongDto> > GetPostFullInfoAsync(int postId, int userId, ERoleType roleType) { Post post = await _unitOfWork.PostRepository.GetSingleAsync(p => p.Id == postId, p => p.Files, p => p.Votes, p => p.Group, p => p.Answers); post.LastVisit = _dateHelper.GetDateTimeUtcNow(); var postVoteType = (EPostVoteType?)post.Votes.FirstOrDefault(v => v.UserId == userId)?.VoteTypeId ?? EPostVoteType.None; if (roleType == ERoleType.Student) { bool isPostAvailable = await _unitOfWork.UserAvailablePostRepository.AnyAsync(up => up.UserId == userId && up.PostId == postId); if (!isPostAvailable) { return(ServiceResult <PostLongDto> .Fail(EOperationResult.ValidationError, "You need to unlock the post first!")); } } var postDto = _mapper.Map <Post, PostLongDto>(post); postDto.UserVoteType = postVoteType; await _unitOfWork.CommitAsync(); return(ServiceResult <PostLongDto> .Ok(postDto)); }
public Task <ServiceResult <UserInformationModel> > LoginAsync(ClientMode mode, string username, string password) { return(Task.Run(() => { if (mode == ClientMode.Offline) { using (var context = _contextFactory.Create()) { var userInfo = context.Employees.FirstOrDefault(e => e.Username == username); if (userInfo == null || userInfo?.Password != password) { return ServiceResult <UserInformationModel> .Fail("Incorrect username/password"); } return ServiceResult.Ok(new UserInformationModel() { ClientMode = mode, FullName = $"{userInfo.LastName} {userInfo.FirstName} {userInfo.MiddleName}", IsSuperUser = userInfo.IsSuperUser, UserId = userInfo.Id }); } } return ServiceResult <UserInformationModel> .Fail("Unsupported client mode login method"); })); }
public async Task <ServiceResult <EditAnimalModel> > AddAsync(EditAnimalModel model) { var entity = new Animal { Name = model.Name, PasswordNo = model.PasswordNo, ImageUrl = model.ImageUrl }; _db.Add(entity); try { await _db.SaveChangesAsync(); return(ServiceResult <EditAnimalModel> .Success(new EditAnimalModel { Id = entity.Id, Name = entity.Name, PasswordNo = entity.PasswordNo, ImageUrl = entity.ImageUrl })); } catch (Exception ex) { //log error return(ServiceResult <EditAnimalModel> .Fail("Internal server error")); } }
/// <summary> /// اعتبار سنجی آدرس کوتاه /// </summary> /// <param name="shortAddress"></param> /// <returns></returns> private ServiceResult ShortAddressValidation(string shortAddress) { if (shortAddress.Length != 10) { return(ServiceResult.Fail("طول لینک کوتاه شده ارسالی باید 10 باشد")); } return(ServiceResult.Ok()); }
/// <summary> /// Assigns a <see cref="ServiceResult"/> object to the args.ReturnValue if there is a <see cref="ValidationException"/> exception. /// </summary> /// <param name="args"></param> public void Execute(MethodExecutionArgs args) { if (args.Exception is not ValidationException exception) { return; } args.FlowBehavior = FlowBehavior.Return; args.ReturnValue = ServiceResult.Fail(exception.Errors.Select(exceptionError => new ServiceError { Code = GetErrorCode(exceptionError.ErrorCode), Description = exceptionError.ErrorMessage }).ToArray()); }
/// <summary> /// اعتبار سنجی آدرس اصلی /// </summary> /// <param name="dto"></param> /// <returns></returns> private ServiceResult FullAddressValidation(CreateLinkDto dto) { string urlPattern = "http[s]?://"; bool IsValidUrlFormat = Regex.Match(dto.FullAddress.ToLower(), urlPattern).Success; if (IsValidUrlFormat) { return(ServiceResult.Ok()); } return(ServiceResult.Fail(message: "فرمت لینک ارسالی اشتباه است" + " - " + "فرمت مورد قبول : http[s]://...")); }
public ServiceResult Update(Product product) { var existsCategory = _categoryRepository.Exists(x => x.Id == product.CategoryId); if (!existsCategory) { return(ServiceResult.Fail(ServiceError.ForeignKeyNotFound(nameof(Product.CategoryId)))); } _productRepository.Update(product); return(ServiceResult.Success()); }
public async Task <ServiceResult> CheckEmailAsync(string email) { var response = await _apiService.DoRequestAsync("POST", UrlHelper.baseUrl + UrlHelper.CheckEmail, new { email = email }); if (response.IsSuccess) { return(ServiceResult.Ok()); } return(ServiceResult.Fail(response.Error)); }
public ServiceResult Add(Product product) { var isCategoryExist = _categoryRepository.Exists(x => x.Id == product.CategoryId); if (!isCategoryExist) { return(ServiceResult.Fail(ServiceError.ForeignKeyNotFound(nameof(Product.CategoryId)))); } product.Id = default; _productRepository.Add(product); return(ServiceResult.Success()); }
public async Task <ServiceResult> RegisterAsync(string username, string password) { var response = await _apiService.DoRequestAsync("POST", UrlHelper.baseUrl + UrlHelper.Register, new { username = username, password = password }); if (response.IsSuccess) { return(ServiceResult.Ok()); } return(ServiceResult.Fail(response.Error)); }
public async Task <ServiceResult> SaveAsync(byte[] image, string latitude, string longitude) { var response = await _apiService.DoPostFileAsync(UrlHelper.baseUrl + UrlHelper.SaveImage, image, new { latitude = latitude, longitude = longitude }); if (response.IsSuccess) { return(ServiceResult.Ok()); } return(ServiceResult.Fail(response.Error)); }
public async Task <ServiceResult> LogoutAsync() { Application.Current.Properties.Remove("token"); await Application.Current.SavePropertiesAsync(); var response = await _apiService.DoRequestAsync("POST", UrlHelper.baseUrl + UrlHelper.Logout, new { }); if (response.IsSuccess) { return(ServiceResult.Ok()); } return(ServiceResult.Fail(response.Error)); }
private async Task <ServiceResult <SubjectDto> > PerformSubjectValidation(int teacherId, int facultyId) { if (!await _unitOfWork.FacultyRepository.IsExistById(facultyId)) { return(ServiceResult <SubjectDto> .Fail(EOperationResult.EntityNotFound, "Faculty with this Id doesn't exist")); } if (!await _unitOfWork.TeacherRepository.IsExistById(teacherId)) { return(ServiceResult <SubjectDto> .Fail(EOperationResult.EntityNotFound, "Teacher with this Id doesn't exist")); } return(ServiceResult <SubjectDto> .Ok()); }
public ServiceResult Create(VacationDto dto) { string message = CheckDates(dto); if (string.IsNullOrWhiteSpace(message)) { Vacation entity = new Vacation(); entity = _mapper.Map <Vacation>(dto); _unitOfWork.GetRepository <Vacation>().Add(entity); _unitOfWork.Commit(); message = "Vacation successfully added."; return(ServiceResult.Ok(message)); } return(ServiceResult.Fail(message)); }
public async Task <ServiceResult> LoginAsync(string username, string password) { var response = await _apiService.DoLoginAsync(username, password); if (response.IsSuccess) { Application.Current.Properties["token"] = response.Message; await Application.Current.SavePropertiesAsync(); return(ServiceResult.Ok()); } else { return(ServiceResult.Fail(response.Error)); } }