public GetQuestionsResponse GetQuestions(GetQuestionsRequest request) { GetQuestionsResponse response = new GetQuestionsResponse(); AuthToken authToken = null; try { Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token"); if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } DbContext context = DataController.CreateDbContext(); IQueryable <E::Question> questions = context.Questions; if (!string.IsNullOrEmpty(request.Name)) { questions = questions.Where(q => q.Name.Contains(request.Name)); } response.TotalCount = questions.Count(); questions = questions.OrderByDescending(a => a.CreatedDate) .Skip(request.StartAt) .Take(InitialRound.Web.Properties.Settings.Default.PageSize); response.Results = questions.AsEnumerable().Select(a => new GetQuestionsResponseItem { ID = a.ID, Name = a.Name, LastUpdatedBy = a.LastUpdatedBy, LastUpdatedDate = a.LastUpdatedDate.ToShortDateString(), CreatedBy = a.CreatedBy, CreatedDate = a.CreatedDate.ToShortDateString() }).ToArray(); } catch (AuthenticationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } return(response); }
public async Task <GetQuestionsResponse> GetQuestionsForOnlineUserAsync(UserLevel userLevel) { return(await GetResponseAsync(async() => { var response = new GetQuestionsResponse(); using (var db = new EFDbContext()) { var questionsQuery = db.Questions.AsNoTracking().Where(x => !x.IsDeleted && x.Level == userLevel).AsQueryable(); switch (userLevel) { case UserLevel.Beginer: questionsQuery = questionsQuery.Take(Constants.BEGINER_QUESTIONS_COUNT); break; case UserLevel.Intermediate: questionsQuery = questionsQuery.Take(Constants.INTERMEDIATE_QUESTIONS_COUNT); break; case UserLevel.Pro: questionsQuery = questionsQuery.Take(Constants.PRO_QUESTIONS_COUNT); break; default: questionsQuery = questionsQuery.Take(Constants.BEGINER_QUESTIONS_COUNT); break; } var questionEntities = await questionsQuery.ToListAsync(); if (questionEntities == null || questionEntities.Count == 0) { throw new Exception("questions not found"); } var questions = questionEntities.Select(x => new ApiQuestion { Id = x.Id, Name = x.Name, Type = x.Type, Level = x.Level, TestAnswer1 = x.TestAnswer1, TestAnswer2 = x.TestAnswer2, TestAnswer3 = x.TestAnswer3, TestAnswer4 = x.TestAnswer4, }).ToList(); response.Questions = questions; } return response; })); }
public async Task <IActionResult> GetQuestion([FromQuery] int pageIndex = 1) { string tokenString = Request.Headers["Authorization"]; int currentUserId = JwtAthentication.GetCurrentUserId(tokenString); var userId = _distributedCache.GetString(currentUserId.ToString()); int NoOfItem = Convert.ToInt32(_configuration["Setting:NumberOfItemNeedToBeCache"]); int pageSize = Convert.ToInt32(_configuration["Setting:PageSize"]); int totalQuestion = 0; string totalQuestionKey = "totalQuestion" + currentUserId.ToString(); List <Question> questions = new List <Question>(); if (!string.IsNullOrEmpty(userId)) { var output = await _distributedCache.GetAsync <IEnumerable <Question> >(currentUserId.ToString()); questions = output.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); questions.ForEach(x => x.AvatarUrl = Url.Content(string.Format("~/Images/UserAvatars/{0}", x.Avatar))); questions.ForEach(x => x.CategoryImageUrl = Url.Content(string.Format("~/Images/Categories/{0}", x.ImageName))); string totalQues = await _distributedCache.GetAsync <string>(totalQuestionKey); totalQuestion = Convert.ToInt32(totalQues); } else { var questionsToCache = _questionService.GetQuestions(currentUserId, NoOfItem, 1, out totalQuestion); questions = questionsToCache.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); questions.ForEach(x => x.AvatarUrl = Url.Content(string.Format("~/Images/UserAvatars/{0}", x.Avatar))); questions.ForEach(x => x.CategoryImageUrl = Url.Content(string.Format("~/Images/Categories/{0}", x.ImageName))); await _distributedCache.SetAsync <IEnumerable <Question> >(currentUserId.ToString(), questionsToCache, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2) }); await _distributedCache.SetAsync <string>(totalQuestionKey, totalQuestion.ToString(), new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2) }); } GetQuestionsResponse response = new GetQuestionsResponse() { Questions = questions, TotalQuestion = totalQuestion }; return(Ok(new { response = response })); }
public IActionResult GetQuestion([FromQuery] int pageIndex = 1) { string tokenString = Request.Headers["Authorization"]; int currentUserId = JwtAthentication.GetCurrentUserId(tokenString); int pageSize = Convert.ToInt32(_configuration["Setting:PageSize"]); int totalQuestion = 0; var questions = _questionService.GetQuestions(currentUserId, pageSize, pageIndex, out totalQuestion).ToList(); questions.ForEach(x => x.AvatarUrl = Url.Content(string.Format("~/Images/UserAvatars/{0}", x.Avatar))); questions.ForEach(x => x.CategoryImageUrl = Url.Content(string.Format("~/Images/Categories/{0}", x.ImageName))); GetQuestionsResponse response = new GetQuestionsResponse() { Questions = questions, TotalQuestion = totalQuestion }; return(Ok(new { response = response })); }
public JsonResult Get(string data, /*[FromBody]string signature, */ [FromQuery] string signature /*, [FromForm]string signature*/) { try { var decodedData = CryptoUtils.Base64Decode(data); var getQuestionsModel = JsonConvert.DeserializeObject <GetQuestions>(decodedData); if (!getQuestionsModel.IsModelValid()) { throw new ErrorWithDataException("Some of the data parameters are invalid. Check the documentation.", Models.Api.StatusCode.WrongData); } var user = _applicationContext.User .Include(u => u.UserProjects) .ThenInclude(up => up.Project) .FirstOrDefault(u => u.UserName == getQuestionsModel.Login); if (user == null)// || user.PasswordHash != questionToApi.PasswordHash) { throw new ErrorWithDataException("User with such email doesn't exist.", Models.Api.StatusCode.WrongLoginPasswordCredentials); } var userProject = user.UserProjects.FirstOrDefault(up => up.Project.Id == getQuestionsModel.ProjectId); if (userProject == null) { throw new ErrorWithDataException("Provided user doesn't consist in the project with such ID.", Models.Api.StatusCode.WrongProjectId); } if (!Utils.ValidateSignature(data, signature, userProject.Project.PrivateKey)) { throw new ErrorWithDataException("Signature is not valid. Check your PrivateKey and MD5 alghorithm.", Models.Api.StatusCode.WrongSignature); } var questionIds = _processorService.GetListOfSimilarQuestionIds(getQuestionsModel.Text, getQuestionsModel.ProjectId, getQuestionsModel.SimilarMaxCount); var questionList = _applicationContext.Questions .Where(q => questionIds.Contains(q.Id)) .Select(q => q.Text) .ToList(); var getQuestionResponse = new GetQuestionsResponse { QuestionText = getQuestionsModel.Text, Questions = questionList, StatusCode = Models.Api.StatusCode.Success, StatusMessage = "List of similar questions." }; return(Json(getQuestionResponse)); } catch (ErrorWithDataException ex) { var answer = new PostQuestionResponse() { StatusCode = ex.StatusCode(), StatusMessage = ex.Message }; return(Json(answer)); } catch (Exception ex) { var answer = new PostQuestionResponse() { StatusCode = Models.Api.StatusCode.Error, StatusMessage = ex.Message }; return(Json(answer)); } }