示例#1
0
        public object Any(Answers request)
        {
            TableRepository tableRepository = new TableRepository();
            CloudTable questionTable = tableRepository.GetTable(Tables.Questions);

            Guid questionId = Guid.Parse(request.Id);

            TableQuery<QuestionEntry> questionQuery = questionTable.CreateQuery<QuestionEntry>();

            QuestionEntry questionEntry = (from k in questionQuery
                                           where k.RowKey == questionId.ToString()
                                           select k).SingleOrDefault();

            if (questionEntry == null)
                throw HttpError.NotFound("Such question do not exist");

            questionEntry.Views++;
            tableRepository.InsertOrMerge(questionEntry, Tables.Questions);

            CloudTable answerTable = tableRepository.GetTable(Tables.Answers);
            TableQuery<AnswerEntry> answerQuery = answerTable.CreateQuery<AnswerEntry>();

            AnswerEntry[] answerEntries = (from k in answerQuery
                                           where k.PartitionKey == questionId.ToString()
                                           select k).ToArray();

            UserQuestionEntry userQuestionEntry = UserSession.IsAuthenticated
                                            ? tableRepository.Get<UserQuestionEntry>(Tables.UserQuestion, questionId, UserSession.GetUserId())
                                            : null;

            HashSet<string> votesUp = new HashSet<string>(userQuestionEntry?.VotesUp?.Split('|') ?? new string[] { });
            HashSet<string> votesDown = new HashSet<string>(userQuestionEntry?.VotesDown?.Split('|') ?? new string[] { });

            Func<Guid, VoteKind> getVoteKind = ownerId =>
                                         {
                                             if (votesUp.Contains(ownerId.ToString()))
                                                 return VoteKind.Up;

                                             if (votesDown.Contains(ownerId.ToString()))
                                                 return VoteKind.Down;

                                             return VoteKind.None;
                                         };

            AnswersResponse answersResponse = new AnswersResponse
            {
                Id = questionEntry.GetId(),
                Creation = questionEntry.Creation,
                Owner = CreateUserCard(tableRepository, questionEntry.GetOwnerId()),
                Detail = questionEntry.Detail,
                Tags = questionEntry.Tags.SplitAndTrimOn(new char[] { ',' }),
                Title = questionEntry.Title,
                Views = questionEntry.Views,
                Votes = questionEntry.Votes,
                SelectedAnswer = questionEntry.SelectedAnswer,
                Answers = answerEntries.Select(k => new AnswerResult
                {
                    Owner = CreateUserCard(tableRepository, k.GetAnswerOwnerId()),
                    Creation = k.Creation,
                    Content = k.Content,
                    Votes = k.Votes,
                    VoteKind = getVoteKind(k.GetAnswerOwnerId())
                }).ToArray()
            };

            // quest user vote for this question
            answersResponse.VoteKind = getVoteKind(questionId);
            answersResponse.Love = userQuestionEntry?.Love ?? false;

            return answersResponse;
        }
示例#2
0
        public IActionResult AnswerQuestion([FromBody] AnswersRequest answersRequest)
        {
            Logger.Debug("Request: {0}", Framework.Common.SerializeJson.ToObject(answersRequest));
            DateTime dateRequest   = DateTime.Now;
            var      response      = new IResponse <AnswersResponse>();
            string   correlationId = string.Empty;

            try
            {
                #region Authorization Usuario y Contraseña
                if (string.IsNullOrEmpty(Request.Headers["Authorization"]))
                {
                    var validate = Models.Response.Error(null, "NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }

                correlationId = Request.Headers["Correlation-Id"].ToString();

                Core.Entity.User user = new Core.Entity.User()
                {
                    Public   = answersRequest.PublicToken,
                    UserName = answersRequest.UserAplication,
                    Password = answersRequest.PasswordAplication
                };
                var userAuthenticate = _user.Authenticate(user);
                if (userAuthenticate.Data == null)
                {
                    var validate = Models.Response.Error("NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                Core.Entity.UserPolicy userPolicy = new Core.Entity.UserPolicy()
                {
                    AppUserId = answersRequest.AppUserId,
                    IdUser    = ((Core.Entity.User)userAuthenticate.Data).Id
                };
                Core.Entity.Policy policy = new Core.Entity.Policy()
                {
                    Name = Request.Path.Value
                };
                var userPolicyAuthorize = _userPolicy.Authorize(userPolicy, policy);
                if (userPolicyAuthorize.Data == null)
                {
                    var validate = Models.Response.Error("NotUnauthorized");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                #endregion

                AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialToken        = authHeader.Parameter;
                var responsetokenValidated = _tokenManager.GetPrincipalFromExpiredToken(credentialToken);

                if (responsetokenValidated.Data == null)
                {
                    response.Data    = null;
                    response.Message = responsetokenValidated.Message;
                    response.State   = responsetokenValidated.State;
                    return(BadRequest(response));
                }
                var principal   = (ClaimsPrincipal)responsetokenValidated.Data;
                var claimList   = principal.Claims.ToList();
                var verifyEmail = claimList[2].Value;

                if (!verifyEmail.Equals(answersRequest.Email.Trim()))
                {
                    var validate = Models.Response.Error("ClientNotSession");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(BadRequest(response));
                }

                var moduleClient = _clientModule.InsertClientModuleAnswers(answersRequest.Email, answersRequest.ModuleNumber, answersRequest.AppUserId);

                if (moduleClient.Data == null)
                {
                    response.Data    = null;
                    response.Message = moduleClient.Message;
                    response.State   = moduleClient.State;
                    return(BadRequest(response));
                }

                var      moduleData          = (Core.Entity.Coupon)moduleClient.Data;
                var      contestDate         = _configuration.GetValue <string>("ContestDate");
                var      separateDate        = contestDate.Split("/");
                DateTime contestDateFormated = new DateTime(Convert.ToInt32(separateDate[2]), Convert.ToInt32(separateDate[1]), Convert.ToInt32(separateDate[0]));
                string   dateInText          = String.Format(new CultureInfo("es-BO"), "{0:D}", contestDateFormated);
                var      messageCoupon       = _configuration.GetValue <string>("Connectors_Email:MessageCoupon");
                _emailmanager.SendEmail(claimList[2].Value, "Finalización de módulo", messageCoupon, messageCoupon, "¡FELICIDADES!", Request.Headers["origin"], "", "", moduleData.CouponNumber, moduleData.CouponRegistred, dateInText);


                AnswersResponse questionAswerResponse = new AnswersResponse()
                {
                    Email = answersRequest.Email
                };
                response.Data    = questionAswerResponse;
                response.Message = Models.Response.CommentMenssage("AnswerRegistred");
                response.State   = "000";
                return(Ok(response));
            }
            catch (Exception ex)
            {
                Logger.Error("Message: {0}; Exception: {1}", ex.Message, Framework.Common.SerializeJson.ToObject(ex));
                response.Data    = null;
                response.Message = "Error General";
                response.State   = "099";
                return(BadRequest(response));
            }
            finally
            {
                DateTime dateResponse = DateTime.Now;
                Core.Entity.ConsumptionHistory consumptionHistory = new Core.Entity.ConsumptionHistory
                {
                    ApiName       = Request.Path.Value,
                    Host          = Dns.GetHostName() + ":" + Request.Host.Port,
                    CorrelationId = correlationId,
                    AppUserId     = "token",
                    Request       = Framework.Common.SerializeJson.ToObject(answersRequest),
                    DateRequest   = dateRequest,
                    Response      = Framework.Common.SerializeJson.ToObject(response),
                    DateResponse  = dateResponse,
                    CodeResponse  = response.State
                };
                _consumptionHistory.Insert(consumptionHistory);
                Logger.Debug("Request: {0} Response: {1}", answersRequest, response);
            }
        }
示例#3
0
        public object Any(Answers request)
        {
            TableRepository tableRepository = new TableRepository();
            CloudTable      questionTable   = tableRepository.GetTable(Tables.Questions);

            Guid questionId = Guid.Parse(request.Id);

            TableQuery <QuestionEntry> questionQuery = questionTable.CreateQuery <QuestionEntry>();

            QuestionEntry questionEntry = (from k in questionQuery
                                           where k.RowKey == questionId.ToString()
                                           select k).SingleOrDefault();

            if (questionEntry == null)
            {
                throw HttpError.NotFound("Such question do not exist");
            }

            questionEntry.Views++;
            tableRepository.InsertOrMerge(questionEntry, Tables.Questions);

            CloudTable answerTable = tableRepository.GetTable(Tables.Answers);
            TableQuery <AnswerEntry> answerQuery = answerTable.CreateQuery <AnswerEntry>();

            AnswerEntry[] answerEntries = (from k in answerQuery
                                           where k.PartitionKey == questionId.ToString()
                                           select k).ToArray();


            UserQuestionEntry userQuestionEntry = UserSession.IsAuthenticated
                                            ? tableRepository.Get <UserQuestionEntry>(Tables.UserQuestion, questionId, UserSession.GetUserId())
                                            : null;

            HashSet <string> votesUp   = new HashSet <string>(userQuestionEntry?.VotesUp?.Split('|') ?? new string[] { });
            HashSet <string> votesDown = new HashSet <string>(userQuestionEntry?.VotesDown?.Split('|') ?? new string[] { });

            Func <Guid, VoteKind> getVoteKind = ownerId =>
            {
                if (votesUp.Contains(ownerId.ToString()))
                {
                    return(VoteKind.Up);
                }

                if (votesDown.Contains(ownerId.ToString()))
                {
                    return(VoteKind.Down);
                }

                return(VoteKind.None);
            };

            AnswersResponse answersResponse = new AnswersResponse
            {
                Id             = questionEntry.GetId(),
                Creation       = questionEntry.Creation,
                Owner          = CreateUserCard(tableRepository, questionEntry.GetOwnerId()),
                Detail         = questionEntry.Detail,
                Tags           = questionEntry.Tags.SplitAndTrimOn(new char[] { ',' }),
                Title          = questionEntry.Title,
                Views          = questionEntry.Views,
                Votes          = questionEntry.Votes,
                SelectedAnswer = questionEntry.SelectedAnswer,
                Answers        = answerEntries.Select(k => new AnswerResult
                {
                    Owner    = CreateUserCard(tableRepository, k.GetAnswerOwnerId()),
                    Creation = k.Creation,
                    Content  = k.Content,
                    Votes    = k.Votes,
                    VoteKind = getVoteKind(k.GetAnswerOwnerId())
                }).ToArray()
            };

            // quest user vote for this question
            answersResponse.VoteKind = getVoteKind(questionId);
            answersResponse.Love     = userQuestionEntry?.Love ?? false;

            return(answersResponse);
        }