public async Task <QuestionCreateCommandResult> ExecuteAsync(QuestionCreateCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(@"CreateQuestionId {questions}").ConfigureAwait(false);

            var id = result[0].GetInteger().ToString();

            var slug         = CreateSlug(command);
            var initialScore = command.CreationDate.Ticks;
            var scoreIncr    = Constant.VoteScore;
            var data         = GetQuestionData(command, user, id, slug, initialScore);

            result = await _channel.ExecuteAsync(@"
                                    SaveQuestion {question} @id @userId @data @tags
                                    IndexQuestion {questions} @id @initialScore
                                    IndexTags {tag} @id @tags @scoreIncr @initialScore
                                    IndexAutoCompleteTags {tag} @tags",
                                                 new
            {
                id,
                data,
                userId = user.Id,
                tags   = command.Tags,
                initialScore,
                scoreIncr
            })
                     .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            result.Last().AssertOK();

            return(new QuestionCreateCommandResult(id, slug));
        }
Пример #2
0
        public async Task <QuestionVoteCommandResult> ExecuteAsync(QuestionVoteCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result =
                await _channel.ExecuteAsync(
                    "VoteQuestion {question} @id @userId @score @upvote",
                    new
            {
                id     = command.QuestionId,
                userId = user.Id,
                score  = command.Upvote ? Constant.VoteScore : 0 - Constant.VoteScore,
                upvote = command.Upvote ? 1 : 0
            })
                .ConfigureAwait(false);

            CheckExceptions(result);

            result = result[0].AsResults();
            var votes = result[0].AsIntegerArray();
            var tags  = result[1].AsStringArray();

            result = await _channel.ExecuteAsync(@"
                                    VoteQuestionGlobally {questions} @id @score
                                    VoteTags {tag} @id @tags @score",
                                                 new
            {
                id    = command.QuestionId,
                score = command.Upvote ? Constant.VoteScore : 0 - Constant.VoteScore,
                tags
            })
                     .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            return(new QuestionVoteCommandResult(votes[0] - votes[1]));
        }
Пример #3
0
        public async Task <QuestionDeleteCommandResult> ExecuteAsync(QuestionDeleteCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result =
                await _channel.ExecuteAsync(
                    "QuestionDelete {question} @id @userId",
                    new
            {
                id     = command.Id,
                userId = user.Id
            })
                .ConfigureAwait(false);

            CheckException(result);

            result = result[0].AsResults();

            var slug = result[0].GetString();
            var tags = result[1].GetStringArray();

            result = await _channel.ExecuteAsync(@"
                                        UnindexQuestion {questions} @id
                                        UnindexQuestionTags {tag} @id @score @tags",
                                                 new
            {
                id = command.Id,
                tags,
                score = Constant.VoteScore
            }).ConfigureAwait(false);

            return(new QuestionDeleteCommandResult(command.Id, slug));
        }
Пример #4
0
        public async Task <AnswerCreateCommandResult> ExecuteAsync(AnswerCreateCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "CreateAnswer {question} @qid @data",
                new
            {
                qid  = command.QuestionId,
                data = GetAnswerData(command, command.QuestionId, user)
            }).ConfigureAwait(false);

            result = result[0].AsResults();
            var aid         = result[0].GetString();
            var quesionData = result[1].GetStringArray();
            var slug        = quesionData[0];
            var ownerId     = quesionData[1];

            if (ownerId != user.Id)
            {
                _channel.Dispatch("NotifyQuestionUpdate {user} @qid @uid",
                                  new
                {
                    qid = command.QuestionId,
                    uid = user.Id
                });
            }
            return(new AnswerCreateCommandResult(command.QuestionId, slug, aid));
        }
Пример #5
0
        public async Task <AnswerViewModel> BuildAsync(AnswerRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "GetAnswer {question} @answerId @userId",
                new
            {
                answerId = request.AnswerId,
                userId   = user.Id
            })
                         .ConfigureAwait(false);

            result = result[0].AsResults();
            var questionStatus = result[3].AsEnum <QuestionStatus>();

            var answer = new AnswerViewModel();

            result[0].AsObjectCollation(answer);
            answer.User           = result[1].GetString();
            answer.QuestionId     = request.QuestionId;
            answer.Editable       = questionStatus == QuestionStatus.Open;
            answer.Votable        = questionStatus == QuestionStatus.Open;
            answer.AuthoredByUser = answer.User == user.Name;
            answer.UpVoted        = GetVote(result[2].GetString());
            return(answer);
        }
Пример #6
0
 protected override async Task RunClient(String userId, IRedisChannel channel, CancellationToken cancel)
 {
     try
     {
         var userKey = "user_" + userId;
         var result  = await channel.ExecuteAsync("incr @key", new { key = userKey }).ConfigureAwait(false);
     }
     catch (ObjectDisposedException)
     {
         Console.Write("[D]");
     }
     catch (TaskCanceledException)
     {
         Console.Write("[C]");
     }
     catch (AggregateException aex)
     {
         foreach (var ex in aex.InnerExceptions)
         {
             Console.Write("[EX: " + ex.Message + "]");
         }
     }
     catch (Exception ex)
     {
         Console.Write("[EX: " + ex.Message + "]");
     }
 }
Пример #7
0
        public async Task <QuestionEditCommandResult> ExecuteAsync(QuestionEditCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var data = GetPatchData(command);

            var result = await _channel.ExecuteAsync(@"
                                        UpdateQuestion {question} @id @userId @data @tags @topic",
                                                     new
            {
                id     = command.Id,
                userId = user.Id,
                data,
                tags  = command.Tags,
                topic = "question-" + command.Id
            })
                         .ConfigureAwait(false);

            CheckException(result);

            result = result[0].AsResults();
            var slug        = result[0].GetString();
            var addedTags   = result[1].GetStringArray();
            var removedTags = result[2].GetStringArray();



            return(new QuestionEditCommandResult(command.Id, slug));
        }
        public async Task <ValidateSessionCommandResult> ExecuteAsync(ValidateSessionCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var sessionDuration = TimeSpan.FromMinutes(5).TotalSeconds;

            var result = await _channel.ExecuteAsync(
                "ValidateSession {user} @SessionId @sessionDuration",
                new { command.SessionId, sessionDuration })
                         .ConfigureAwait(false);

            var error = result[0].GetException();

            if (error != null)
            {
                switch (error.Prefix)
                {
                case "NOTVALID":
                    return(ValidateSessionCommandResult.NonValid);

                default: throw error;
                }
            }
            result = result[0].AsResults();

            return(new ValidateSessionCommandResult(result[0].GetString(), result[1].GetString(), (Int32)result[2].GetInteger()));
        }
Пример #9
0
        public async Task <QuestionViewModel> BuildAsync(QuestionRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "QuestionRequest {question} @id @userId",
                new
            {
                id     = request.Id,
                userId = user.Id
            })
                         .ConfigureAwait(false);

            CheckException(result);

            var complex  = result[0].AsResults();
            var question = new QuestionViewModel();

            complex[0].AsObjectCollation(question);

            question.User           = complex[1].GetString();
            question.Tags           = complex[2].GetStringArray();
            question.Id             = request.Id;
            question.AuthoredByUser = question.User == user.Name;
            question.UpVoted        = GetVote(complex[3].GetString());
            question.UserVotedClose = complex[4].AsInteger() == 1;

            question.Answers = ExtractAnswers(user, complex[5].AsResults(), question);

            return(question);
        }
Пример #10
0
        protected override async Task RunClient(String userId, IRedisChannel channel, CancellationToken cancel)
        {
            try
            {
                var userKey = "user_" + userId;

                foreach (var dummy in _data)
                {
                    var result = await channel.ExecuteAsync("hmset @key @data", new { key = userId + "_" + dummy.Id, data = Parameter.SequenceProperties(dummy) }).ConfigureAwait(false);

                    result.ThrowErrorIfAny();
                }

                foreach (var dummy in _data)
                {
                    var result = await channel.ExecuteAsync(@"
                                                    hgetall @key
                                                    del @key",
                                                            new { key = userId + "_" + dummy.Id })
                                 .ConfigureAwait(false);

                    result.ThrowErrorIfAny();
                    var readed = result[0].AsObjectCollation <DummyClass>();
                }
            }
            catch (ObjectDisposedException)
            {
                Console.Write("[D]");
            }
            catch (TaskCanceledException)
            {
                Console.Write("[C]");
            }
            catch (AggregateException aex)
            {
                foreach (var ex in aex.InnerExceptions)
                {
                    Console.Write("[EX: " + ex.Message + "]");
                }
            }
            catch (Exception ex)
            {
                Console.Write("[EX: " + ex.Message + "]");
            }
        }
Пример #11
0
        // Dummy authentication
        public async Task <AuthenticateCommandResult> ExecuteAsync(AuthenticateCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            // Preventing user from login in with a user from a data dump
            // because markdown code is missing and cannto be edited
            if (user.Name != "dumpprocessor")
            {
                var ismember = await _channel.ExecuteAsync("SISMEMBER {user}:builtin @user", new { user = command.Username }).ConfigureAwait(false);

                if (ismember[0].GetInteger() == 1)
                {
                    throw new SimpleQAAuthenticationException("It is a built-in user.");
                }
            }

            var session         = GenerateLOLRandomIdentifier();
            var newid           = GenerateLOLRandomIdentifier();
            var sessionDuration = TimeSpan.FromMinutes(5).TotalSeconds;


            var result = await _channel.ExecuteAsync(
                "Authenticate {user} @username @newid @session @sessionduration",
                new
            {
                username = command.Username,
                newid,
                session,
                sessionDuration
            })
                         .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            var userId = result[0].GetString();

            // This should be done during registration
            // but since this demo uses dummy authenticaion
            // is done here.
            await _channel.ExecuteAsync(
                "HSET {question}:uidmapping @userId @username",
                new { userId, username = command.Username })
            .ConfigureAwait(false);

            return(new AuthenticateCommandResult(session));
        }
        public async Task <PopularTagsViewModel> BuildAsync(PopularTagsRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync("GetPopularTags {tag} @count",
                                                     new { count = 20 })
                         .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            return(new PopularTagsViewModel()
            {
                Tags = result[0].GetStringArray()
            });
        }
Пример #13
0
        public async Task <UserInboxModel> BuildAsync(UserInboxRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "GetInboxNotifications {user} @userId",
                new { userId = user.Id })
                         .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            var ids = result[0].GetStringArray();
            List <QuestionNotification> list;

            if (ids.Any())
            {
                list = await GetQuestions(ids).ConfigureAwait(false);
            }
            else
            {
                list = new List <QuestionNotification>();
            }
            return(new UserInboxModel(list));
        }
Пример #14
0
        public async Task <TagSuggestionsModel> BuildAsync(TagSuggestionRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "SuggestTags {tag} @prefix @max",
                new
            {
                prefix = request.Query,
                max    = 100
            }).ConfigureAwait(false);

            result.ThrowErrorIfAny();
            return(new TagSuggestionsModel(result[0].GetStringArray().Take(10).ToArray()));
        }
        public async Task <HomeByTagViewModel> BuildAsync(HomeByTagRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var model = new HomeByTagViewModel();

            var sorting = request.Sorting.HasValue ? request.Sorting.Value : QuestionSorting.ByScore;

            var result =
                await _channel.ExecuteAsync(
                    "PaginateTag {tag} @tag @page @items @orderBy",
                    new
            {
                tag     = request.Tag,
                page    = request.Page - 1,
                items   = Constant.ItemsPerPage,
                orderBy = sorting.ToString()
            })
                .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            result = result[0].AsResults();

            model.Page       = request.Page;
            model.TotalPages = (Int32)Math.Ceiling(result[0].AsInteger() / (Constant.ItemsPerPage * 1.0));
            model.Sorting    = sorting;
            model.Tag        = request.Tag;

            var ids = result.Skip(1).Select(r => r.GetString()).ToArray();

            if (ids.Any())
            {
                model.Questions = await GetQuestions(ids).ConfigureAwait(false);
            }
            else
            {
                model.Questions = new List <QuestionExcerptViewModel>();
            }

            return(model);
        }
        public async Task <AnswerDeleteCommandResult> ExecuteAsync(AnswerDeleteCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "DeleteAnswer {question} @answerId @userId",
                new
            {
                answerId = command.AnswerId,
                userId   = user.Id
            })
                         .ConfigureAwait(false);

            CheckException(result);
            var slug = result[0].GetString();

            return(new AnswerDeleteCommandResult(command.QuestionId, slug));
        }
Пример #17
0
        public async Task <QuestionCloseFormViewModel> BuildAsync(QuestionCloseFormRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "QuestionCloseForm {question} @id",
                new
            {
                id = request.Id
            })
                         .ConfigureAwait(false);

            result.ThrowErrorIfAny();
            return(new QuestionCloseFormViewModel()
            {
                Id = request.Id, Votes = result[0].AsInteger()
            });
        }
Пример #18
0
        public async Task <AnswerVoteCommandResult> ExecuteAsync(AnswerVoteCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "VoteAswer {question} @answerId @userId @vote",
                new
            {
                answerId = command.AnswerId,
                userId   = user.Id,
                vote     = command.Upvote ? "1" : "-1"
            })
                         .ConfigureAwait(false);

            CheckExceptions(result);
            var votes = result[0].AsIntegerArray();

            return(new AnswerVoteCommandResult(votes[0] - votes[1]));
        }
        public async Task <QuestionCloseCommandResult> ExecuteAsync(QuestionCloseCommand command, SimpleQAIdentity user, CancellationToken cancel)
        {
            var votesToClose = Constant.CloseVotesRequired;

            var result = await _channel.ExecuteAsync(
                "QuestionClose {question} @id @userId @votesToClose",
                new
            {
                id     = command.Id,
                userId = user.Id,
                votesToClose
            })
                         .ConfigureAwait(false);

            CheckException(result);

            return(new QuestionCloseCommandResult(command.Id, result[0].GetString()));
        }
Пример #20
0
        public async Task <AnswerEditFormViewModel> BuildAsync(AnswerEditFormRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "GetAnswerEditData {question} @answerId @userID",
                new
            {
                answerId = request.AnswerId,
                userId   = user.Id
            })
                         .ConfigureAwait(false);

            CheckException(result);
            return(new AnswerEditFormViewModel()
            {
                AnswerId = request.AnswerId,
                QuestionId = request.QuestionId,
                Content = result[0].GetString()
            });
        }
        public async Task <QuestionEditFormViewModel> BuildAsync(QuestionEditFormRequest request, SimpleQAIdentity user, CancellationToken cancel)
        {
            var result = await _channel.ExecuteAsync(
                "QuestionEditForm {question} @id @userId",
                new
            {
                id     = request.Id,
                userId = user.Id
            })
                         .ConfigureAwait(false);

            CheckException(result);

            result = result[0].AsResults();

            var model = new QuestionEditFormViewModel();

            model.Content = result[0].GetString();
            model.Title   = result[1].GetString();
            model.Tags    = result[2].GetStringArray();
            model.Id      = request.Id;
            return(model);
        }
Пример #22
0
 /// <summary>
 /// Executes asynchronously the given command.
 /// </summary>
 /// <param name="channel"><see cref="IRedisChannel"/></param>
 /// <param name="command">The Redis command.</param>
 /// <param name="cancel">A token that can cancel the execution.</param>
 public static Task <IRedisResults> ExecuteAsync(this IRedisChannel channel, String command, CancellationToken cancel)
 {
     return(channel.ExecuteAsync <Object>(command, null, cancel));
 }
Пример #23
0
 /// <summary>
 /// Executes asynchronously the given command.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="channel"><see cref="IRedisChannel"/></param>
 /// <param name="command">The Redis command.</param>
 /// <param name="parameters">The object with properties will be used as parameters.</param>
 public static Task <IRedisResults> ExecuteAsync <T>(this IRedisChannel channel, String command, T parameters) where T : class
 {
     return(channel.ExecuteAsync(command, parameters, CancellationToken.None));
 }