From d53caaea6094136bac3d01ce9dd2782bb1819fe2 Mon Sep 17 00:00:00 2001 From: transtrike Date: Thu, 25 Mar 2021 12:22:54 +0200 Subject: Profile Picture implemented; Tests and Front end work await --- .../Repositories/ProfilePictureRepository.cs | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/Data/DevHive.Data/Repositories/ProfilePictureRepository.cs (limited to 'src/Data/DevHive.Data/Repositories') diff --git a/src/Data/DevHive.Data/Repositories/ProfilePictureRepository.cs b/src/Data/DevHive.Data/Repositories/ProfilePictureRepository.cs new file mode 100644 index 0000000..7284464 --- /dev/null +++ b/src/Data/DevHive.Data/Repositories/ProfilePictureRepository.cs @@ -0,0 +1,25 @@ +using System.Threading.Tasks; +using DevHive.Data.Interfaces; +using DevHive.Data.Models; +using Microsoft.EntityFrameworkCore; + +namespace DevHive.Data.Repositories +{ + public class ProfilePictureRepository : BaseRepository, IProfilePictureRepository + { + private readonly DevHiveContext _context; + + public ProfilePictureRepository(DevHiveContext context) + : base(context) + { + this._context = context; + } + + public async Task GetByURLAsync(string picUrl) + { + return await this._context + .ProfilePicture + .FirstOrDefaultAsync(x => x.PictureURL == picUrl); + } + } +} -- cgit v1.2.3 From 0cf2a3c99141f878168271e53999cdacac95f3c4 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 29 Mar 2021 13:03:10 +0300 Subject: Fixed warnings for commented code and async cloudinary method --- src/Data/DevHive.Data/Repositories/PostRepository.cs | 3 --- src/Services/DevHive.Services/Services/CloudinaryService.cs | 3 +++ 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/Data/DevHive.Data/Repositories') diff --git a/src/Data/DevHive.Data/Repositories/PostRepository.cs b/src/Data/DevHive.Data/Repositories/PostRepository.cs index 0a88cf2..b5228c2 100644 --- a/src/Data/DevHive.Data/Repositories/PostRepository.cs +++ b/src/Data/DevHive.Data/Repositories/PostRepository.cs @@ -60,7 +60,6 @@ namespace DevHive.Data.Repositories public override async Task EditAsync(Guid id, Post newEntity) { Post post = await this.GetByIdAsync(id); - // var ratingId = post.Rating.Id; this._context .Entry(post) @@ -76,8 +75,6 @@ namespace DevHive.Data.Repositories foreach (var comment in newEntity.Comments) post.Comments.Add(comment); - // post.Rating.Id = ratingId; - this._context.Entry(post).State = EntityState.Modified; return await this.SaveChangesAsync(); diff --git a/src/Services/DevHive.Services/Services/CloudinaryService.cs b/src/Services/DevHive.Services/Services/CloudinaryService.cs index 6e2e975..05600cc 100644 --- a/src/Services/DevHive.Services/Services/CloudinaryService.cs +++ b/src/Services/DevHive.Services/Services/CloudinaryService.cs @@ -52,6 +52,9 @@ namespace DevHive.Services.Services public async Task RemoveFilesFromCloud(List fileUrls) { + // Workaround, this method isn't fully implemented yet + await Task.Run(null); + return true; } } -- cgit v1.2.3 From da7d6223c261aac8e8f18458c11fb48cf9ca4cfe Mon Sep 17 00:00:00 2001 From: transtrike Date: Mon, 5 Apr 2021 13:41:31 +0300 Subject: Introduced consts for every string possible. FML --- .../DevHive.Common/Constants/ClassesConstants.cs | 22 +++++++ .../DevHive.Common/Constants/ErrorMessages.cs | 16 +++++ src/Data/DevHive.Data.Models/Comment.cs | 4 -- .../DevHive.Data/Repositories/RatingRepository.cs | 10 ++-- .../DevHive.Services.Tests/UserService.Tests.cs | 2 +- .../DevHive.Services/Services/CloudinaryService.cs | 30 +++++----- .../DevHive.Services/Services/CommentService.cs | 29 ++++----- .../DevHive.Services/Services/FeedService.cs | 14 +++-- .../DevHive.Services/Services/LanguageService.cs | 12 ++-- .../DevHive.Services/Services/PostService.cs | 41 ++++++------- .../Services/ProfilePictureService.cs | 18 +++--- .../DevHive.Services/Services/RatingService.cs | 17 +++--- .../DevHive.Services/Services/RoleService.cs | 12 ++-- .../DevHive.Services/Services/TechnologyService.cs | 12 ++-- .../DevHive.Services/Services/UserService.cs | 69 ++++++++++++---------- 15 files changed, 177 insertions(+), 131 deletions(-) create mode 100644 src/Common/DevHive.Common/Constants/ClassesConstants.cs create mode 100644 src/Common/DevHive.Common/Constants/ErrorMessages.cs (limited to 'src/Data/DevHive.Data/Repositories') diff --git a/src/Common/DevHive.Common/Constants/ClassesConstants.cs b/src/Common/DevHive.Common/Constants/ClassesConstants.cs new file mode 100644 index 0000000..825f737 --- /dev/null +++ b/src/Common/DevHive.Common/Constants/ClassesConstants.cs @@ -0,0 +1,22 @@ +namespace DevHive.Common.Constants +{ + public static class ClassesConstants + { + public const string Data = "Data"; + + public const string Post = "The Post"; + public const string Comment = "The Comment"; + public const string User = "The User"; + public const string Language = "The Language"; + public const string Picture = "The Picture"; + public const string Files = "The Files"; + public const string Rating = "The Rating"; + public const string Role = "The Role"; + public const string Technology = "The Technology"; + + public const string Username = "The Username"; + public const string Email = "The Email"; + public const string Password = "Password"; + public const string OneOrMoreFriends = "One or more Friends"; + } +} diff --git a/src/Common/DevHive.Common/Constants/ErrorMessages.cs b/src/Common/DevHive.Common/Constants/ErrorMessages.cs new file mode 100644 index 0000000..30ca544 --- /dev/null +++ b/src/Common/DevHive.Common/Constants/ErrorMessages.cs @@ -0,0 +1,16 @@ +namespace DevHive.Common.Constants +{ + public static class ErrorMessages + { + public const string InvalidData = "Invalid {0}!"; + public const string IncorrectData = "Incorrect {0}!"; + public const string DoesNotExist = "{0} does not exist!"; + public const string AlreadyExists = "{0} already exists!"; + + public const string CannotAdd = "Could not add {0}!"; + public const string CannotCreate = "Could not create {0}!"; + public const string CannotDelete = "Could not delete {0}!"; + public const string CannotUpload = "Could not upload {0}!"; + public const string CannotEdit = "Could not edit {0}!"; + } +} diff --git a/src/Data/DevHive.Data.Models/Comment.cs b/src/Data/DevHive.Data.Models/Comment.cs index 0af40bf..8a58edd 100644 --- a/src/Data/DevHive.Data.Models/Comment.cs +++ b/src/Data/DevHive.Data.Models/Comment.cs @@ -6,12 +6,8 @@ namespace DevHive.Data.Models { public Guid Id { get; set; } - // public Guid PostId { get; set; } - public Post Post { get; set; } - // public Guid CreatorId { get; set; } - public User Creator { get; set; } public string Message { get; set; } diff --git a/src/Data/DevHive.Data/Repositories/RatingRepository.cs b/src/Data/DevHive.Data/Repositories/RatingRepository.cs index c35f6d5..2048c3f 100644 --- a/src/Data/DevHive.Data/Repositories/RatingRepository.cs +++ b/src/Data/DevHive.Data/Repositories/RatingRepository.cs @@ -11,13 +11,11 @@ namespace DevHive.Data.Repositories public class RatingRepository : BaseRepository, IRatingRepository { private readonly DevHiveContext _context; - private readonly IPostRepository _postRepository; - public RatingRepository(DevHiveContext context, IPostRepository postRepository) + public RatingRepository(DevHiveContext context) : base(context) { this._context = context; - this._postRepository = postRepository; } public override async Task GetByIdAsync(Guid id) @@ -28,7 +26,7 @@ namespace DevHive.Data.Repositories .FirstOrDefaultAsync(x => x.Id == id); } /// - /// Gets all the ratings for a psot. + /// Gets all the ratings for a post. /// /// Id of the post. /// @@ -40,10 +38,10 @@ namespace DevHive.Data.Repositories .Where(x => x.Post.Id == postId).ToListAsync(); } /// - /// Checks if a user rated a given post. In DevHive every user has one or no rating for every post. + /// Checks if a user rated a given post. In DevHive every user has one or no rating for every post. /// /// Id of the user. - /// Id of the psot. + /// Id of the post. /// True if the user has already rated the post and false if he hasn't. public async Task UserRatedPost(Guid userId, Guid postId) { diff --git a/src/Services/DevHive.Services.Tests/UserService.Tests.cs b/src/Services/DevHive.Services.Tests/UserService.Tests.cs index 7990b32..9d1bca5 100644 --- a/src/Services/DevHive.Services.Tests/UserService.Tests.cs +++ b/src/Services/DevHive.Services.Tests/UserService.Tests.cs @@ -344,7 +344,7 @@ namespace DevHive.Services.Tests // } // else // { - // const string EXCEPTION_MESSAGE = "Unable to edit user!"; + // const string EXCEPTION_MESSAGE = string.Format(ErrorMessages.CannotEdit, ClassesConstants.User.ToLower()); // // Exception ex = Assert.ThrowsAsync(() => this._userService.UpdateUser(updateUserServiceModel); // diff --git a/src/Services/DevHive.Services/Services/CloudinaryService.cs b/src/Services/DevHive.Services/Services/CloudinaryService.cs index 05600cc..078bb5d 100644 --- a/src/Services/DevHive.Services/Services/CloudinaryService.cs +++ b/src/Services/DevHive.Services/Services/CloudinaryService.cs @@ -14,7 +14,7 @@ namespace DevHive.Services.Services { // Regex for getting the filename without (final) filename extension // So, from image.png, it will match image, and from doc.my.txt will match doc.my - private static Regex _imageRegex = new Regex(".*(?=\\.)"); + private static readonly Regex s_imageRegex = new(".*(?=\\.)"); private readonly Cloudinary _cloudinary; @@ -28,23 +28,21 @@ namespace DevHive.Services.Services List fileUrls = new(); foreach (var formFile in formFiles) { - string fileName = _imageRegex.Match(formFile.FileName).ToString(); + string fileName = s_imageRegex.Match(formFile.FileName).ToString(); - using (var ms = new MemoryStream()) + using var ms = new MemoryStream(); + formFile.CopyTo(ms); + byte[] formBytes = ms.ToArray(); + + RawUploadParams rawUploadParams = new() { - formFile.CopyTo(ms); - byte[] formBytes = ms.ToArray(); - - RawUploadParams rawUploadParams = new() - { - File = new FileDescription(fileName, new MemoryStream(formBytes)), - PublicId = fileName, - UseFilename = true - }; - - RawUploadResult rawUploadResult = await this._cloudinary.UploadAsync(rawUploadParams); - fileUrls.Add(rawUploadResult.Url.AbsoluteUri); - } + File = new FileDescription(fileName, new MemoryStream(formBytes)), + PublicId = fileName, + UseFilename = true + }; + + RawUploadResult rawUploadResult = await this._cloudinary.UploadAsync(rawUploadParams); + fileUrls.Add(rawUploadResult.Url.AbsoluteUri); } return fileUrls; diff --git a/src/Services/DevHive.Services/Services/CommentService.cs b/src/Services/DevHive.Services/Services/CommentService.cs index b48bac8..1c388f6 100644 --- a/src/Services/DevHive.Services/Services/CommentService.cs +++ b/src/Services/DevHive.Services/Services/CommentService.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; +using DevHive.Data.Interfaces; using DevHive.Data.Models; -using DevHive.Services.Models.Comment; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces; -using System.Linq; +using DevHive.Services.Models.Comment; namespace DevHive.Services.Services { @@ -31,7 +32,7 @@ namespace DevHive.Services.Services public async Task AddComment(CreateCommentServiceModel createCommentServiceModel) { if (!await this._postRepository.DoesPostExist(createCommentServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Comment comment = this._postMapper.Map(createCommentServiceModel); comment.TimeCreated = DateTime.Now; @@ -56,10 +57,10 @@ namespace DevHive.Services.Services public async Task GetCommentById(Guid id) { Comment comment = await this._commentRepository.GetByIdAsync(id) ?? - throw new ArgumentException("The comment does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); User user = await this._userRepository.GetByIdAsync(comment.Creator.Id) ?? - throw new ArgumentException("The user does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); ReadCommentServiceModel readCommentServiceModel = this._postMapper.Map(comment); readCommentServiceModel.IssuerFirstName = user.FirstName; @@ -74,7 +75,7 @@ namespace DevHive.Services.Services public async Task UpdateComment(UpdateCommentServiceModel updateCommentServiceModel) { if (!await this._commentRepository.DoesCommentExist(updateCommentServiceModel.CommentId)) - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); Comment comment = this._postMapper.Map(updateCommentServiceModel); comment.TimeCreated = DateTime.Now; @@ -95,7 +96,7 @@ namespace DevHive.Services.Services public async Task DeleteComment(Guid id) { if (!await this._commentRepository.DoesCommentExist(id)) - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); Comment comment = await this._commentRepository.GetByIdAsync(id); return await this._commentRepository.DeleteAsync(comment); @@ -121,7 +122,7 @@ namespace DevHive.Services.Services public async Task ValidateJwtForComment(Guid commentId, string rawTokenData) { Comment comment = await this._commentRepository.GetByIdAsync(commentId) ?? - throw new ArgumentException("Comment does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); User user = await this.GetUserForValidation(rawTokenData); //If user made the comment @@ -141,10 +142,10 @@ namespace DevHive.Services.Services { JwtSecurityToken jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7)); - Guid jwtUserId = Guid.Parse(this.GetClaimTypeValues("ID", jwt.Claims).First()); + Guid jwtUserId = Guid.Parse(GetClaimTypeValues("ID", jwt.Claims).First()); User user = await this._userRepository.GetByIdAsync(jwtUserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return user; } @@ -152,7 +153,7 @@ namespace DevHive.Services.Services /// /// Returns all values from a given claim type /// - private List GetClaimTypeValues(string type, IEnumerable claims) + private static List GetClaimTypeValues(string type, IEnumerable claims) { List toReturn = new(); diff --git a/src/Services/DevHive.Services/Services/FeedService.cs b/src/Services/DevHive.Services/Services/FeedService.cs index 0af8093..9c622b3 100644 --- a/src/Services/DevHive.Services/Services/FeedService.cs +++ b/src/Services/DevHive.Services/Services/FeedService.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -26,10 +28,11 @@ namespace DevHive.Services.Services /// /// This method is used in the feed page. - /// See the FeedRepository "GetFriendsPosts" menthod for more information on how it works. + /// See the FeedRepository "GetFriendsPosts" method for more information on how it works. /// public async Task GetPage(GetPageServiceModel getPageServiceModel) { + //TODO: Rework the initialization of User User user = null; if (getPageServiceModel.UserId != Guid.Empty) @@ -37,10 +40,10 @@ namespace DevHive.Services.Services else if (!string.IsNullOrEmpty(getPageServiceModel.Username)) user = await this._userRepository.GetByUsernameAsync(getPageServiceModel.Username); else - throw new ArgumentException("Invalid given data!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); if (user == null) - throw new ArgumentException("User doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); List posts = await this._feedRepository .GetFriendsPosts(user.Friends.ToList(), getPageServiceModel.FirstRequestIssued, getPageServiceModel.PageNumber, getPageServiceModel.PageSize); @@ -58,15 +61,16 @@ namespace DevHive.Services.Services /// public async Task GetUserPage(GetPageServiceModel model) { + //TODO: Rework the initialization of User User user = null; if (!string.IsNullOrEmpty(model.Username)) user = await this._userRepository.GetByUsernameAsync(model.Username); else - throw new ArgumentException("Invalid given data!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); if (user == null) - throw new ArgumentException("User doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); List posts = await this._feedRepository .GetUsersPosts(user, model.FirstRequestIssued, model.PageNumber, model.PageSize); diff --git a/src/Services/DevHive.Services/Services/LanguageService.cs b/src/Services/DevHive.Services/Services/LanguageService.cs index 9d2041e..7ee7d9f 100644 --- a/src/Services/DevHive.Services/Services/LanguageService.cs +++ b/src/Services/DevHive.Services/Services/LanguageService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -24,7 +26,7 @@ namespace DevHive.Services.Services public async Task CreateLanguage(CreateLanguageServiceModel createLanguageServiceModel) { if (await this._languageRepository.DoesLanguageNameExistAsync(createLanguageServiceModel.Name)) - throw new ArgumentException("Language already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); Language language = this._languageMapper.Map(createLanguageServiceModel); bool success = await this._languageRepository.AddAsync(language); @@ -45,7 +47,7 @@ namespace DevHive.Services.Services Language language = await this._languageRepository.GetByIdAsync(id); if (language == null) - throw new ArgumentException("The language does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Language)); return this._languageMapper.Map(language); } @@ -65,10 +67,10 @@ namespace DevHive.Services.Services bool newLangNameExists = await this._languageRepository.DoesLanguageNameExistAsync(languageServiceModel.Name); if (!langExists) - throw new ArgumentException("Language does not exist!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); if (newLangNameExists) - throw new ArgumentException("Language name already exists in our data base!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Language)); Language lang = this._languageMapper.Map(languageServiceModel); return await this._languageRepository.EditAsync(languageServiceModel.Id, lang); @@ -79,7 +81,7 @@ namespace DevHive.Services.Services public async Task DeleteLanguage(Guid id) { if (!await this._languageRepository.DoesLanguageExistAsync(id)) - throw new ArgumentException("Language does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Language)); Language language = await this._languageRepository.GetByIdAsync(id); return await this._languageRepository.DeleteAsync(language); diff --git a/src/Services/DevHive.Services/Services/PostService.cs b/src/Services/DevHive.Services/Services/PostService.cs index a565473..8580e82 100644 --- a/src/Services/DevHive.Services/Services/PostService.cs +++ b/src/Services/DevHive.Services/Services/PostService.cs @@ -1,15 +1,16 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; -using AutoMapper; -using DevHive.Data.Models; -using DevHive.Services.Models.Post; using System.IdentityModel.Tokens.Jwt; +using System.Linq; using System.Security.Claims; -using DevHive.Services.Interfaces; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; -using System.Linq; +using DevHive.Data.Models; using DevHive.Data.Models.Relational; +using DevHive.Services.Interfaces; +using DevHive.Services.Models.Post; namespace DevHive.Services.Services { @@ -34,7 +35,7 @@ namespace DevHive.Services.Services public async Task CreatePost(CreatePostServiceModel createPostServiceModel) { if (!await this._userRepository.DoesUserExistAsync(createPostServiceModel.CreatorId)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); Post post = this._postMapper.Map(createPostServiceModel); @@ -66,7 +67,7 @@ namespace DevHive.Services.Services public async Task GetPostById(Guid id) { Post post = await this._postRepository.GetByIdAsync(id) ?? - throw new ArgumentException("The post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); // This can't happen in repo, because of how time is usually compared post.Comments = post.Comments @@ -74,7 +75,7 @@ namespace DevHive.Services.Services .ToList(); User user = await this._userRepository.GetByIdAsync(post.Creator.Id) ?? - throw new ArgumentException("The user does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); int currentRating = 0; foreach (Rating rating in post.Ratings) @@ -100,7 +101,7 @@ namespace DevHive.Services.Services public async Task UpdatePost(UpdatePostServiceModel updatePostServiceModel) { if (!await this._postRepository.DoesPostExist(updatePostServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Post post = this._postMapper.Map(updatePostServiceModel); @@ -111,11 +112,11 @@ namespace DevHive.Services.Services List fileUrlsToRemove = await this._postRepository.GetFileUrls(updatePostServiceModel.PostId); bool success = await _cloudService.RemoveFilesFromCloud(fileUrlsToRemove); if (!success) - throw new InvalidCastException("Could not delete files from the post!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Files.ToLower())); } List fileUrls = await _cloudService.UploadFilesToCloud(updatePostServiceModel.Files) ?? - throw new ArgumentException("Unable to upload images to cloud!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotUpload, ClassesConstants.Files.ToLower())); post.Attachments = GetPostAttachmentsFromUrls(post, fileUrls); } @@ -136,7 +137,7 @@ namespace DevHive.Services.Services public async Task DeletePost(Guid id) { if (!await this._postRepository.DoesPostExist(id)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); Post post = await this._postRepository.GetByIdAsync(id); @@ -145,7 +146,7 @@ namespace DevHive.Services.Services List fileUrls = await this._postRepository.GetFileUrls(id); bool success = await _cloudService.RemoveFilesFromCloud(fileUrls); if (!success) - throw new InvalidCastException("Could not delete files from the post. Please try again"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Files.ToLower())); } return await this._postRepository.DeleteAsync(post); @@ -158,7 +159,7 @@ namespace DevHive.Services.Services /// public async Task ValidateJwtForCreating(Guid userId, string rawTokenData) { - User user = await this.GetUserForValidation(rawTokenData); + User user = await GetUserForValidation(rawTokenData); return user.Id == userId; } @@ -171,8 +172,8 @@ namespace DevHive.Services.Services public async Task ValidateJwtForPost(Guid postId, string rawTokenData) { Post post = await this._postRepository.GetByIdAsync(postId) ?? - throw new ArgumentException("Post does not exist!"); - User user = await this.GetUserForValidation(rawTokenData); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); + User user = await GetUserForValidation(rawTokenData); //If user made the post if (post.Creator.Id == user.Id) @@ -192,8 +193,8 @@ namespace DevHive.Services.Services public async Task ValidateJwtForComment(Guid commentId, string rawTokenData) { Comment comment = await this._commentRepository.GetByIdAsync(commentId) ?? - throw new ArgumentException("Comment does not exist!"); - User user = await this.GetUserForValidation(rawTokenData); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Comment)); + User user = await GetUserForValidation(rawTokenData); //If user made the comment if (comment.Creator.Id == user.Id) @@ -215,7 +216,7 @@ namespace DevHive.Services.Services Guid jwtUserId = Guid.Parse(GetClaimTypeValues("ID", jwt.Claims).First()); User user = await this._userRepository.GetByIdAsync(jwtUserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return user; } diff --git a/src/Services/DevHive.Services/Services/ProfilePictureService.cs b/src/Services/DevHive.Services/Services/ProfilePictureService.cs index 1de2114..cafa7cb 100644 --- a/src/Services/DevHive.Services/Services/ProfilePictureService.cs +++ b/src/Services/DevHive.Services/Services/ProfilePictureService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -33,14 +34,13 @@ namespace DevHive.Services.Services await ValidateUserExistsAsync(profilePictureServiceModel.UserId); User user = await this._userRepository.GetByIdAsync(profilePictureServiceModel.UserId); - // if (user.ProfilePicture.PictureURL != ProfilePicture.DefaultURL) if (user.ProfilePicture.Id != Guid.Empty) { List file = new() { user.ProfilePicture.PictureURL }; bool removed = await this._cloudinaryService.RemoveFilesFromCloud(file); if (!removed) - throw new ArgumentException("Cannot delete old picture"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); } return await SaveProfilePictureInDatabase(profilePictureServiceModel); @@ -49,16 +49,16 @@ namespace DevHive.Services.Services public async Task DeleteProfilePicture(Guid id) { ProfilePicture profilePic = await this._profilePictureRepository.GetByIdAsync(id) ?? - throw new ArgumentException("Such picture doesn't exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Picture)); bool removedFromDb = await this._profilePictureRepository.DeleteAsync(profilePic); if (!removedFromDb) - throw new ArgumentException("Cannot delete picture from database!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); List file = new() { profilePic.PictureURL }; bool removedFromCloud = await this._cloudinaryService.RemoveFilesFromCloud(file); if (!removedFromCloud) - throw new ArgumentException("Cannot delete picture from cloud!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotDelete, ClassesConstants.Picture.ToLower())); return true; } @@ -75,13 +75,13 @@ namespace DevHive.Services.Services bool success = await this._profilePictureRepository.AddAsync(profilePic); if (!success) - throw new ArgumentException("Unable to upload picture!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotUpload, ClassesConstants.Files.ToLower())); user.ProfilePicture = profilePic; bool userProfilePicAlter = await this._userRepository.EditAsync(user.Id, user); if (!userProfilePicAlter) - throw new ArgumentException("Unable to alter user's profile picture"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotEdit, "user's profile picture")); return picUrl; } @@ -89,13 +89,13 @@ namespace DevHive.Services.Services private static void ValidateProfPic(IFormFile profilePictureFormFile) { if (profilePictureFormFile.Length == 0) - throw new ArgumentException("Picture cannot be null"); + throw new ArgumentNullException(nameof(profilePictureFormFile), string.Format(ErrorMessages.InvalidData, ClassesConstants.Data.ToLower())); } private async Task ValidateUserExistsAsync(Guid userId) { if (!await this._userRepository.DoesUserExistAsync(userId)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); } } } diff --git a/src/Services/DevHive.Services/Services/RatingService.cs b/src/Services/DevHive.Services/Services/RatingService.cs index 9d8f4b0..d6b4299 100644 --- a/src/Services/DevHive.Services/Services/RatingService.cs +++ b/src/Services/DevHive.Services/Services/RatingService.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -19,6 +16,8 @@ namespace DevHive.Services.Services private readonly IRatingRepository _ratingRepository; private readonly IMapper _mapper; + private const string NotRated = "{0} has not rated" + ClassesConstants.Post; + public RatingService(IPostRepository postRepository, IRatingRepository ratingRepository, IUserRepository userRepository, IMapper mapper) { this._postRepository = postRepository; @@ -31,7 +30,7 @@ namespace DevHive.Services.Services public async Task RatePost(CreateRatingServiceModel createRatingServiceModel) { if (!await this._postRepository.DoesPostExist(createRatingServiceModel.PostId)) - throw new ArgumentException("Post does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Post)); if (await this._ratingRepository.UserRatedPost(createRatingServiceModel.UserId, createRatingServiceModel.PostId)) throw new ArgumentException("User already rated the post!"); @@ -84,13 +83,13 @@ namespace DevHive.Services.Services public async Task UpdateRating(UpdateRatingServiceModel updateRatingServiceModel) { Rating rating = await this._ratingRepository.GetRatingByUserAndPostId(updateRatingServiceModel.UserId, updateRatingServiceModel.PostId) ?? - throw new ArgumentException("Rating does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Rating)); User user = await this._userRepository.GetByIdAsync(updateRatingServiceModel.UserId) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); if (!await this._ratingRepository.UserRatedPost(updateRatingServiceModel.UserId, updateRatingServiceModel.PostId)) - throw new ArgumentException("User has not rated the post!"); + throw new ArgumentException(string.Format(NotRated, ClassesConstants.User)); rating.User = user; rating.IsLike = updateRatingServiceModel.IsLike; @@ -111,7 +110,7 @@ namespace DevHive.Services.Services public async Task DeleteRating(Guid ratingId) { if (!await this._ratingRepository.DoesRatingExist(ratingId)) - throw new ArgumentException("Rating does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Rating)); Rating rating = await this._ratingRepository.GetByIdAsync(ratingId); return await this._ratingRepository.DeleteAsync(rating); diff --git a/src/Services/DevHive.Services/Services/RoleService.cs b/src/Services/DevHive.Services/Services/RoleService.cs index a5da759..f61181a 100644 --- a/src/Services/DevHive.Services/Services/RoleService.cs +++ b/src/Services/DevHive.Services/Services/RoleService.cs @@ -1,6 +1,8 @@ using System; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -22,7 +24,7 @@ namespace DevHive.Services.Services public async Task CreateRole(CreateRoleServiceModel createRoleServiceModel) { if (await this._roleRepository.DoesNameExist(createRoleServiceModel.Name)) - throw new ArgumentException("Role already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role)); Role role = this._roleMapper.Map(createRoleServiceModel); bool success = await this._roleRepository.AddAsync(role); @@ -40,7 +42,7 @@ namespace DevHive.Services.Services public async Task GetRoleById(Guid id) { Role role = await this._roleRepository.GetByIdAsync(id) ?? - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); return this._roleMapper.Map(role); } @@ -48,10 +50,10 @@ namespace DevHive.Services.Services public async Task UpdateRole(UpdateRoleServiceModel updateRoleServiceModel) { if (!await this._roleRepository.DoesRoleExist(updateRoleServiceModel.Id)) - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); if (await this._roleRepository.DoesNameExist(updateRoleServiceModel.Name)) - throw new ArgumentException("Role name already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role)); Role role = this._roleMapper.Map(updateRoleServiceModel); return await this._roleRepository.EditAsync(updateRoleServiceModel.Id, role); @@ -60,7 +62,7 @@ namespace DevHive.Services.Services public async Task DeleteRole(Guid id) { if (!await this._roleRepository.DoesRoleExist(id)) - throw new ArgumentException("Role does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); Role role = await this._roleRepository.GetByIdAsync(id); return await this._roleRepository.DeleteAsync(role); diff --git a/src/Services/DevHive.Services/Services/TechnologyService.cs b/src/Services/DevHive.Services/Services/TechnologyService.cs index 09c4d20..4cf84c5 100644 --- a/src/Services/DevHive.Services/Services/TechnologyService.cs +++ b/src/Services/DevHive.Services/Services/TechnologyService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Data; using System.Threading.Tasks; using AutoMapper; +using DevHive.Common.Constants; using DevHive.Data.Interfaces; using DevHive.Data.Models; using DevHive.Services.Interfaces; @@ -24,7 +26,7 @@ namespace DevHive.Services.Services public async Task CreateTechnology(CreateTechnologyServiceModel technologyServiceModel) { if (await this._technologyRepository.DoesTechnologyNameExistAsync(technologyServiceModel.Name)) - throw new ArgumentException("Technology already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Technology)); Technology technology = this._technologyMapper.Map(technologyServiceModel); bool success = await this._technologyRepository.AddAsync(technology); @@ -45,7 +47,7 @@ namespace DevHive.Services.Services Technology technology = await this._technologyRepository.GetByIdAsync(id); if (technology == null) - throw new ArgumentException("The technology does not exist"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); return this._technologyMapper.Map(technology); } @@ -62,10 +64,10 @@ namespace DevHive.Services.Services public async Task UpdateTechnology(UpdateTechnologyServiceModel updateTechnologyServiceModel) { if (!await this._technologyRepository.DoesTechnologyExistAsync(updateTechnologyServiceModel.Id)) - throw new ArgumentException("Technology does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); if (await this._technologyRepository.DoesTechnologyNameExistAsync(updateTechnologyServiceModel.Name)) - throw new ArgumentException("Technology name already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Technology)); Technology technology = this._technologyMapper.Map(updateTechnologyServiceModel); bool result = await this._technologyRepository.EditAsync(updateTechnologyServiceModel.Id, technology); @@ -78,7 +80,7 @@ namespace DevHive.Services.Services public async Task DeleteTechnology(Guid id) { if (!await this._technologyRepository.DoesTechnologyExistAsync(id)) - throw new ArgumentException("Technology does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Technology)); Technology technology = await this._technologyRepository.GetByIdAsync(id); bool result = await this._technologyRepository.DeleteAsync(technology); diff --git a/src/Services/DevHive.Services/Services/UserService.cs b/src/Services/DevHive.Services/Services/UserService.cs index d487de4..62576d4 100644 --- a/src/Services/DevHive.Services/Services/UserService.cs +++ b/src/Services/DevHive.Services/Services/UserService.cs @@ -1,15 +1,17 @@ -using AutoMapper; -using DevHive.Services.Models.User; -using System.Threading.Tasks; -using DevHive.Data.Models; using System; using System.Collections.Generic; -using DevHive.Common.Models.Identity; -using DevHive.Services.Interfaces; -using DevHive.Data.Interfaces; +using System.Data; +using System.IO; using System.Linq; -using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Common.Constants; using DevHive.Common.Jwt.Interfaces; +using DevHive.Common.Models.Identity; +using DevHive.Data.Interfaces; +using DevHive.Data.Models; +using DevHive.Services.Interfaces; +using DevHive.Services.Models.User; namespace DevHive.Services.Services { @@ -20,15 +22,17 @@ namespace DevHive.Services.Services private readonly ILanguageRepository _languageRepository; private readonly ITechnologyRepository _technologyRepository; private readonly IMapper _userMapper; - private readonly ICloudService _cloudService; private readonly IJwtService _jwtService; + private const string NoYourselfAsFriend = "You cant add yourself as a friend(sry, bro)!"; + private const string Rant = "Can't promote shit in this country..."; + + public UserService(IUserRepository userRepository, ILanguageRepository languageRepository, IRoleRepository roleRepository, ITechnologyRepository technologyRepository, IMapper mapper, - ICloudService cloudService, IJwtService jwtService) { this._userRepository = userRepository; @@ -36,7 +40,6 @@ namespace DevHive.Services.Services this._userMapper = mapper; this._languageRepository = languageRepository; this._technologyRepository = technologyRepository; - this._cloudService = cloudService; this._jwtService = jwtService; } @@ -44,12 +47,12 @@ namespace DevHive.Services.Services public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName)) - throw new ArgumentException("Invalid username!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, ClassesConstants.Username)); User user = await this._userRepository.GetByUsernameAsync(loginModel.UserName); if (!await this._userRepository.VerifyPassword(user, loginModel.Password)) - throw new ArgumentException("Incorrect password!"); + throw new InvalidDataException(string.Format(ErrorMessages.IncorrectData, ClassesConstants.Password.ToLower())); List roleNames = user.Roles.Select(x => x.Name).ToList(); return new TokenModel(this._jwtService.GenerateJwtToken(user.Id, user.UserName, roleNames)); @@ -58,10 +61,11 @@ namespace DevHive.Services.Services public async Task RegisterUser(RegisterServiceModel registerModel) { if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName)) - throw new ArgumentException("Username already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Username)); if (await this._userRepository.DoesEmailExistAsync(registerModel.Email)) - throw new ArgumentException("Email already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Email)); + User user = this._userMapper.Map(registerModel); @@ -69,9 +73,9 @@ namespace DevHive.Services.Services bool roleResult = await this._userRepository.AddRoleToUser(user, Role.DefaultRole); if (!userResult) - throw new ArgumentException("Unable to create a user"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotCreate, ClassesConstants.User.ToLower())); if (!roleResult) - throw new ArgumentException("Unable to add role to user"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotAdd, ClassesConstants.Role.ToLower())); User createdUser = await this._userRepository.GetByUsernameAsync(registerModel.UserName); @@ -84,7 +88,7 @@ namespace DevHive.Services.Services public async Task GetUserById(Guid id) { User user = await this._userRepository.GetByIdAsync(id) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return this._userMapper.Map(user); } @@ -92,7 +96,7 @@ namespace DevHive.Services.Services public async Task GetUserByUsername(string username) { User user = await this._userRepository.GetByUsernameAsync(username) ?? - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); return this._userMapper.Map(user); } @@ -101,20 +105,20 @@ namespace DevHive.Services.Services #region Update public async Task UpdateUser(UpdateUserServiceModel updateUserServiceModel) { - await this.ValidateUserOnUpdate(updateUserServiceModel); + await ValidateUserOnUpdate(updateUserServiceModel); User user = await this._userRepository.GetByIdAsync(updateUserServiceModel.Id); - await this.PopulateUserModel(user, updateUserServiceModel); + await PopulateUserModel(user, updateUserServiceModel); if (updateUserServiceModel.Friends.Count > 0) - await this.CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); + await CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); else user.Friends.Clear(); bool result = await this._userRepository.EditAsync(user.Id, user); if (!result) - throw new InvalidOperationException("Unable to edit user!"); + throw new InvalidOperationException(string.Format(ErrorMessages.CannotEdit, ClassesConstants.User.ToLower())); User newUser = await this._userRepository.GetByIdAsync(user.Id); return this._userMapper.Map(newUser); @@ -125,7 +129,7 @@ namespace DevHive.Services.Services public async Task DeleteUser(Guid id) { if (!await this._userRepository.DoesUserExistAsync(id)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); User user = await this._userRepository.GetByIdAsync(id); return await this._userRepository.DeleteAsync(user); @@ -140,21 +144,21 @@ namespace DevHive.Services.Services private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel) { if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id)) - throw new ArgumentException("User does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User)); if (updateUserServiceModel.Friends.Any(x => x.UserName == updateUserServiceModel.UserName)) - throw new ArgumentException("You cant add yourself as a friend(sry, bro)!"); + throw new InvalidOperationException(NoYourselfAsFriend); if (!await this._userRepository.DoesUserHaveThisUsernameAsync(updateUserServiceModel.Id, updateUserServiceModel.UserName) && await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName)) - throw new ArgumentException("Username already exists!"); + throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Username.ToLower())); List usernames = new(); foreach (var friend in updateUserServiceModel.Friends) usernames.Add(friend.UserName); if (!await this._userRepository.ValidateFriendsCollectionAsync(usernames)) - throw new ArgumentException("One or more friends do not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.OneOrMoreFriends)); } #endregion @@ -162,7 +166,7 @@ namespace DevHive.Services.Services public async Task SuperSecretPromotionToAdmin(Guid userId) { User user = await this._userRepository.GetByIdAsync(userId) ?? - throw new ArgumentException("User does not exist! Can't promote shit in this country..."); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.User) + " " + Rant); if (!await this._roleRepository.DoesNameExist(Role.AdminRole)) { @@ -202,7 +206,7 @@ namespace DevHive.Services.Services foreach (var role in updateUserServiceModel.Roles) { Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ?? - throw new ArgumentException($"Role {role.Name} does not exist!"); + throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role)); roles.Add(returnedRole); } @@ -214,7 +218,7 @@ namespace DevHive.Services.Services for (int i = 0; i < languagesCount; i++) { Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid language name!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, nameof(Language))); languages.Add(language); } @@ -226,7 +230,8 @@ namespace DevHive.Services.Services for (int i = 0; i < technologiesCount; i++) { Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ?? - throw new ArgumentException("Invalid technology name!"); + throw new InvalidDataException(string.Format(ErrorMessages.InvalidData, nameof(Technology))); + technologies.Add(technology); } -- cgit v1.2.3