public RatingDTO GetPersonalRatingOfMedia(int userId, int mediaId) { RatingDTO rating = null; try { MySqlCommand command = new MySqlCommand("SELECT * FROM `rating` WHERE UserId = @userId AND MediaId = @mediaId", _conn); command.Parameters.AddWithValue("userId", userId); command.Parameters.AddWithValue("mediaId", mediaId); _conn.Open(); MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { rating = new RatingDTO( reader.GetInt32("UserId"), reader.GetInt32("MediaId"), reader.GetInt32("Rating") ); } } catch (Exception e) { Console.WriteLine(e); throw; } finally { _conn.Close(); } return(rating); }
private async void RemoveUserRating(RatingDTO rating) { var ratings = await RatingFacade.ListRatingsAsync(new RatingFilterDTO { SearchedRatedUsersId = new[] { rating.RatedUserId } }); int ratingsCount = ratings.Items.Count(); if (rating.RatedUserRole == UserRole.Corporation) { var corporation = await UserFacade.GetCorporationAsync(rating.RatedUserId); corporation.SumRating = DecreaseRating(corporation.SumRating.Value, ratingsCount, rating.Score); corporation.RatingCount -= 1; await UserFacade.EditCorporationAsync(corporation); } else { var freelancer = await UserFacade.GetFreelancerAsync(rating.RatedUserId); freelancer.SumRating = DecreaseRating(freelancer.SumRating.Value, ratingsCount, rating.Score); freelancer.RatingCount -= 1; await UserFacade.EditFreelancerAsync(freelancer); } }
public async Task <bool> UpdateRating(RatingDTO viewmodel) { string uri = string.Format("update"); var categories = await client.GetResponseObject <RatingDTO, bool>(uri, eHttpMethodType.PUT, viewmodel); return(categories); }
public async Task <int> CreateRatingAsync(RatingDTO rating) { using (var uow = UnitOfWorkProvider.Create()) { if (rating.RatedUserRole == UserRole.Corporation) { var corporation = await corporationService.GetAsync(rating.RatedUserId); if (!corporation.SumRating.HasValue) { corporation.SumRating = 0; } corporation.SumRating += rating.Score; corporation.RatingCount += 1; await corporationService.Update(corporation); } else { var freelancer = await freelancerService.GetAsync(rating.RatedUserId); if (!freelancer.SumRating.HasValue) { freelancer.SumRating = 0; } freelancer.SumRating += rating.Score; freelancer.RatingCount += 1; await freelancerService.Update(freelancer); } var ratingId = ratingService.Create(rating); await uow.Commit(); return(ratingId); } }
public RatingDTO GetInternshipRatingsAverege(int id) { using (var uow = new UnitOfWork()) { var ratings = uow.RatingRepository.getDbSet().Where(t => t.InternshipId == id).ToList(); if (ratings == null) { throw new Exception("Nu exista evaluari pentru acest internship!"); } RatingDTO finalRating = new RatingDTO(); ratings.ForEach(r => { finalRating.RatingCompany += r.RatingCompany; finalRating.RatingInternship += r.RatingInternship; finalRating.RatingMentors += r.RatingMentors; }); finalRating.RatingCompany /= (float)ratings.Count; finalRating.RatingInternship /= (float)ratings.Count; finalRating.RatingMentors /= (float)ratings.Count; return(finalRating); } }
public async Task <IActionResult> Rate(int id, double averageRating, [FromQuery] int?appointmentId = null) { if (string.IsNullOrEmpty(CurrentUserName)) { return(Unauthorized()); } // Get Current UserId Here (From Token) var user = await _userService.GetPersonByMobileAsync(CurrentUserName); if (user == null) { throw new AwroNoreException(NewResource.UserNotFound); } var rateModel = new RatingDTO { UserId = user.Id, ServiceSupplyId = id, AppointmentId = appointmentId, AverageRating = averageRating }; await _doctorsService.RateDoctorAsync(rateModel); return(Ok()); }
public async Task <List <MovieDTO> > Search(OmdbSearchRequestDTO searchRequest) { var queryDictionary = new Dictionary <string, string>(); queryDictionary.Add("s", searchRequest.SearchQuery); queryDictionary.Add("apiKey", "2f3362ff"); var queryString = queryDictionary.ToQueryString(); var endpoint = OmdbEndpoints.SEARCH_MOVIES.DescriptionAttr() + queryString; var ombdResults = await ApiRequest.Make(uri, endpoint); var movieResults = ombdResults.OmdbResultToApiResult(); var movieResultIds = movieResults.Select(_ => _.ImdbId); var ratings = _context.Ratings; var movieRatings = new List <Rating>(); if (ratings.Any()) { movieRatings = _context.Ratings.Where(_ => movieResultIds.Any(mrid => mrid == _.Movie.ImdbId)).ToList(); } if (movieRatings.Any()) { movieResults.Select(_ => { var rating = movieRatings.FirstOrDefault(mr => mr.Movie.ImdbId == _.ImdbId); _.UserRating = RatingDTO.Populate(rating); return(_); }); } return(movieResults); }
public async Task <Response <string> > SetRatingAsync(string userName, RatingDTO ratingDTO) { var response = new Response <string>(); var ratingObjDB = await _db.Ratings .AsNoTracking() .Where(r => r.userName == userName && r.slideName == ratingDTO.slideName) .FirstOrDefaultAsync(); if (ratingObjDB == null) { var ratingObj = new Rating() { userName = userName, slideName = ratingDTO.slideName, ratingValue = ratingDTO.ratingValue }; await _db.Ratings.AddAsync(ratingObj); } else { ratingObjDB.ratingValue = ratingDTO.ratingValue; _db.Ratings.Update(ratingObjDB); } await _db.SaveChangesAsync(); response.Data = "Rating is success saved!"; return(response); }
public async Task <MovieDTO> GetOne(MovieDTO movie, UserDTO user) { var queryDictionary = new Dictionary <string, string>(); queryDictionary.Add("i", movie.ImdbId); queryDictionary.Add("apiKey", "2f3362ff"); var queryString = queryDictionary.ToQueryString(); var endpoint = OmdbEndpoints.GET_ONE_MOVIE.DescriptionAttr() + queryString; var ombdResult = await ApiRequest.Make(uri, endpoint); var movieResult = ombdResult.OmdbResultToMovieDTO(); var movieRating = _context.Ratings.FirstOrDefault(_ => _.Movie.ImdbId == movie.ImdbId && _.User.Id == user.Id); if (movieRating != null) { movieResult.UserRating = RatingDTO.Populate(movieRating); } else { movieResult.UserRating = new RatingDTO { Score = DB.Score.UNRATED }; } return(movieResult); }
/// <summary> /// Updates a rating made by the user with the given ID for a book with the given /// ID from the database, returns the updated review /// </summary> public ReviewViewModel UpdateReviewByUser(RatingDTO rating, int userID, int bookID) { var user = _db.Friends.SingleOrDefault(u => u.ID == userID); if (user == null) { throw new ObjectNotFoundException("User with the given ID was not found"); } var book = _db.Books.SingleOrDefault(b => b.ID == bookID); if (book == null) { throw new ObjectNotFoundException("Book with the given ID was not found"); } var oldReview = (from r in _db.Reviews where r.bookID == bookID && r.friendID == userID select r).SingleOrDefault(); if (oldReview == null) { throw new RatingException("No review by user with the given ID for a book with the given ID has been made"); } oldReview.Rating = rating.Rating; _db.Reviews.Update(oldReview); _db.SaveChanges(); var review = new ReviewViewModel { BookTitle = book.Title, AuthorFirstName = book.FirstName, AuthorLastName = book.LastName, Rating = oldReview.Rating }; return(review); }
public static RatingDTO CreateRating(int ratedId, int creatorId, UserRole creatorUserRole, UserRole ratedUserRole, FormCollection collection) { var newRating = new RatingDTO(); newRating.RatedUserId = ratedId; newRating.RatedUserRole = ratedUserRole; newRating.CreatorId = creatorId; newRating.CreatorRole = creatorUserRole; foreach (string key in collection.AllKeys) { switch (key) { case "Rating.Comment": newRating.Comment = collection[key]; break; case "Rating.Score": if (Int32.TryParse(collection[key], out int value)) { newRating.Score = CorrectedScore(value); } break; } ; } return(newRating); }
// GET: BeerTasters/Details/5 public ActionResult Review(int beerid) { RatingDTO model = new RatingDTO(); model.beerid = beerid; return(View("BeerRatingView", model)); }
public void MapperRatingDTO(RatingDTO rating) { this.Id = rating.Id.ToString(); this.Rate = rating.Rate; this.User = rating.User.GetDTO(); this.CarrierRate = rating.Carrier.GetDTO(); }
public async Task <ActionResult> AddRating(RatingViewModel ratingVM) { if (ModelState.IsValid) { ratingVM.UserId = User.Identity.GetUserId(); RatingDTO rDto = await ratingService.FindByUserIdAsync(ratingVM.UserId); if (rDto != null) { await ratingService.DeleteByIdAsync(rDto.Id); } Mapper.Initialize(cfg => cfg.CreateMap <RatingViewModel, RatingDTO>()); RatingDTO ratingDto = Mapper.Map <RatingViewModel, RatingDTO>(ratingVM); OperationDetails result = await ratingService.CreateAsync(ratingDto); RatingDTO r = await ratingService.FindByUserIdAsync(ratingVM.UserId); if (result.Succeeded) { return(RedirectToAction("MyAlbums", "Album")); } else { ModelState.AddModelError(result.Property, result.Message); } } return(View(ratingVM)); }
public async Task <ActionResult> Post([FromBody] RatingDTO ratingDTO) { //by extracting the value from the JWT we cna be sure of the truth of it, //you could for example totry to get the email from the front end , but it would be possible to forge //this way we know that JWT was constructed using the secret key and the email can be trusted var email = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "email").Value; var user = await userManager.FindByEmailAsync(email); var userId = user.Id; var currentRate = await dbContext.Ratings .FirstOrDefaultAsync(x => x.MovieId == ratingDTO.MovieId && x.UserId == userId); if (currentRate == null) { var rating = new Rating(); rating.MovieId = ratingDTO.MovieId; rating.Rate = ratingDTO.Rating; rating.UserId = userId; dbContext.Add(rating); } else { currentRate.Rate = ratingDTO.Rating; } await dbContext.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> UpDownVotePost(int id, [FromBody] RatingDTO rating) { if (id != rating.Id) { return(NotFound()); } var accountId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var post = await _repo.GetOneWithCondition <Post>(post => post.Id == id); var postRatingFromDb = await _repo.GetOneWithCondition <PostRating>(post => post.AccountId == accountId && post.PostId == id); if (postRatingFromDb == null) { var postUpvote = new PostRating() { PostId = id, AccountId = accountId, Rating = rating.Rating, Date = DateTime.Now }; _repo.Create(postUpvote); } else { postRatingFromDb.Rating = rating.Rating; postRatingFromDb.Date = DateTime.Now; } if (await _repo.SaveAll()) { return(Ok()); } return(StatusCode(500)); }
public async Task <ActionResult> Post([FromBody] RatingDTO ratingDTO) { var email = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "email").Value; var usuario = await userManager.FindByEmailAsync(email); var usuarioId = usuario.Id; var ratingActual = context.Ratings .FirstOrDefault(x => x.PeliculaId == ratingDTO.PeliculaId && x.UsuarioId == usuarioId); if (ratingActual == null) { var rating = new Rating(); rating.PeliculaId = ratingDTO.PeliculaId; rating.Puntuacion = ratingDTO.Puntuacion; rating.UsuarioId = usuarioId; context.Add(rating); } else { ratingActual.Puntuacion = ratingDTO.Puntuacion; } await context.SaveChangesAsync(); return(NoContent()); }
public void WillCallTheDbProviderToUpdateTheUserWithTheNewScore() { Mock <BoardGame> mockGame = new Mock <BoardGame>(); Mock <NodeService> mockService = new Mock <NodeService>(); Move move = new Move(); move.owner = (PlayerColour)100; Mock <INode> mockNode = new Mock <INode>(); mockNode.Setup(x => x.getMove()) .Returns(move); mockNode.Setup(x => x.getReward()) .Returns(-1); mockService.Setup(x => x.process(It.IsAny <BoardGame>(), (PlayerColour)100)) .Returns(new List <INode> { mockNode.Object }); Mock <IDatabaseProvider> mockProvider = new Mock <IDatabaseProvider>(); RatingDTO returned = new RatingDTO(); mockProvider.Setup(x => x.updateUser(0, -1)) .Returns(returned); service = new GameService(mockService.Object, mockProvider.Object); RatingDTO result = service.rateMove(mockGame.Object, move, 0, null); Assert.AreSame(returned, result); }
public RatingDTO rateMove(BoardGame boardGame, Move move, int UserId, Move lastMove) { RatingDTO result = null; boardGame.registerMove(lastMove); boardGame.validateBoard(); double high = -1; double low = 1; List <INode> nodes = nodeService.process(boardGame, (PlayerColour)move.owner); foreach (INode node in nodes) { double reward = node.getReward(); if (reward > high) { high = reward; } if (reward < low) { low = reward; } if (node.getMove().Equals(move)) { result = provider.updateUser(UserId, node.getReward()); provider.saveMove(UserId, node.getReward(), nodes.FindIndex(x => x == node)); if (result != null) { result.highOption = high; result.lowOption = low; } } } return(result); }
public async Task <ActionResult> Post([FromBody] RatingDTO ratingDTO) { var email = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "email").Value; var user = await userManager.FindByEmailAsync(email); var userId = user.Id; var currentRating = await context.Ratings .FirstOrDefaultAsync(x => x.movieId == ratingDTO.movieId && x.userId == userId); if (currentRating == null) { var rating = new Rating(); rating.movieId = ratingDTO.movieId; rating.score = ratingDTO.score; rating.userId = userId; context.Add(rating); } else { currentRating.score = ratingDTO.score; } await context.SaveChangesAsync(); return(NoContent()); }
public ActionResult <RatingDTO> GetAverageRatingsForCurrentCompany() { var companyUserId = User.GetUserId(); var companyId = _companyService.GetCompanyIdForUser(companyUserId); RatingDTO ratingDTO = _ratingService.getAverageRatings(companyId); return(Ok(ratingDTO)); }
//one to dal public static Rating ToDAL(RatingDTO item) { return(new Rating() { doseId = item.doseId, userId = item.userId, rate = item.rate }); }
public async Task <ActionResult> Edit(RatingDTO rating) { var repo = new TasterRepository(); //need to POST the data to API await repo.SaveRating(rating); //potentially with viewbag for extra information return(RedirectToAction("Index"));; }
public static RatingsStatisticsViewModel ToViewModel(RatingDTO rating) { return(new RatingsStatisticsViewModel() { RatingCompany = rating.RatingCompany, RatingMentors = rating.RatingMentors, RatingInternship = rating.RatingInternship }); }
public static RatingDTO ToModel(this Rating rating) { RatingDTO entityRating = new RatingDTO() { Id = rating.Id, Value = rating.Value, }; return(entityRating); }
private RatingDTO ConvertToRatingDTO(RatingViewModel ratingViewModel) { var ratingDTO = new RatingDTO(ratingViewModel.Id); ratingDTO.Rate = ratingViewModel.Rate; ratingDTO.Description = ratingViewModel.Description; ratingDTO.User = base.UserBase; ratingDTO.Carrier = _ratingService.GetCarrierById(ratingViewModel.CarrierId); return(ratingDTO); }
public async Task <IActionResult> RateAsync([FromBody] RatingDTO ratingDTO) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _service.RateAsync(ratingDTO); return(Ok(result)); }
public async Task <RatingDTO> BarRatingAsync(RatingDTO barRatingDTO) { var barRating = this.barRatingMapper.MapFrom(barRatingDTO); await this.context.BarRatings.AddAsync(barRating); await this.context.SaveChangesAsync(); return(barRatingDTO); }
public INode makeMove(BoardGame game, List <INode> nodes, int opponentId) { RatingDTO rating = provider.getUser(opponentId) ?? new RatingDTO(); rating.userId = -1; INode decided = decideMove(game, nodes, rating); decided.getMove().setOwner(getColour()); return(decided); }
public async Task Rate(CommandContext ctx, int uco, string code, byte rating, params string[] content) { var positives = new List<string>(); var negatives = new List<string>(); var comment = new List<string>(); ParseContent(content, positives, negatives, comment); var whome = uco == 0 ? code : uco.ToString(); var builder = new DiscordEmbedBuilder() { Color = DiscordColor.Green, Description = printableContent(positives, negatives, comment, rating), Timestamp = DateTimeOffset.Now, Title = $"Raing for {whome}" }; var ratingMessage = await ctx.RespondAsync(embed: builder.Build()); RatingDTO ratingObj = new RatingDTO(string.Join(' ', comment), string.Join(';', positives), string.Join(';', negatives), rating, uco, code); var jsonRating = JsonSerializer.Serialize<RatingDTO>(ratingObj); await ctx.RespondAsync(jsonRating); var optionReactions = new[] {DiscordEmoji.FromName(ctx.Client, ":thumbsup:"), DiscordEmoji.FromName(ctx.Client, ":thumbsdown:") }; foreach (var t in optionReactions) { await ratingMessage.CreateReactionAsync(t).ConfigureAwait(false); } var interaction = ctx.Client.GetInteractivityModule(); Thread.Sleep(5000); var result = await interaction .WaitForMessageReactionAsync(ratingMessage, ctx.Member, new TimeSpan(0,0,20)); var results = result.Emoji; if (results.GetDiscordName() == ":+1:") { var response = PostRating(ratingObj); await ctx.RespondAsync(response.StatusCode + response.Content + response.ErrorMessage); await ratingMessage.DeleteAsync(); } else if (results.GetDiscordName() == ":-1:") { //aaaaaaaaa why the f**k u wont delete ??? await ctx.Channel.DeleteMessageAsync(ratingMessage); } //Thread.Sleep(5000); //await ctx.Message.DeleteAsync(); //ctx.Message.DeleteAsync("shouldnt be there"); }