Пример #1
0
        public int DownvotePost(string userId, int postId)
        {
            var _userAlreadyUpvoted = UserAlreadyUpvoted(userId, postId);

            if (_userAlreadyUpvoted == null)
            {
                var model = new PostState()
                {
                    PostId = postId,
                    UserId = userId,
                    Vote   = false
                };
                Add(model);
                return(_postService.DecrementUpvote(postId));
            }

            var upvote = _userAlreadyUpvoted.Vote;

            if (!upvote)
            {
                return(_userAlreadyUpvoted.Post.Upvotes);
            }

            _userAlreadyUpvoted.Vote = false;
            _context.SaveChanges();
            return(_postService.DecrementUpvote(postId));
        }
Пример #2
0
 public static PostState SendComment(PostState state, SendCommentAction action)
 {
     return(state with
     {
         ClientPosts = state.ClientPosts
     });
 }
Пример #3
0
 public static PostState GetPostsSingleUser(PostState state, GetPostsSingleUserAction action)
 {
     return(state with
     {
         ClientPosts = state.ClientPosts
     });
 }
Пример #4
0
        async public Task CreateSeed()
        {
            var rootId = Guid.Empty;
            var post   = new Post()
            {
                Title       = string.Empty,
                Source      = string.Empty,
                Content     = string.Empty,
                Description = string.Empty,
                Creator     = "System",
                Modifier    = "System",
                ModifyDate  = DateTimeOffset.MinValue,
                CreateDate  = DateTimeOffset.MinValue,
            };

            var state = new PostState()
            {
                Owner = new User()
                {
                    Id = new Guid(), Email = string.Empty
                },
                Level     = 0,
                EndDate   = DateTime.MaxValue,
                StartDate = DateTime.MinValue
            };
            await _factory.Post(state.SetPost(post));
        }
Пример #5
0
        public ActionResult ReviewSubmission(int id, PostState review)
        {
            PostManager mgr = new PostManager();

            var response = mgr.GetById(id);

            if (response.Success)
            {
                response.Payload.PostState = review;

                var reviewResponse = mgr.EditPost(response.Payload);

                if (reviewResponse.Success)
                {
                    return(RedirectToAction("ViewSubmissions"));
                }
                else
                {
                    throw new Exception(reviewResponse.Message);
                }
            }
            else
            {
                throw new Exception(response.Message);
            }
        }
Пример #6
0
 public static PostState GetPosts(PostState state, GetPostsAction action)
 {
     return(state with
     {
         ClientPosts = state.ClientPosts
     });
 }
Пример #7
0
 //处理失败
 private void ProcessFailed(PostState postState)
 {
     if (isSubmitDataAndImage)
     {
         //uploadProgressBar.gameObject.SetActive(false);//如果失败,同样隐藏进度条
         Debug.Log("上传失败");
         isSubmitDataAndImage = false;
     }
 }
 protected Post(string fullName, string name)
 {
     title    = string.Empty;
     text     = string.Empty;
     created  = new System.DateTime();
     tags     = new HashSet <string>();
     comments = new List <Comment>();
     votes    = new Vote();
     state    = new PostState();
 }
Пример #9
0
        public static PostState SendPostSuccess(PostState state, SendPostSuccessAction action)
        {
            var posts = state.ClientPosts;

            posts.Insert(0, action.NewPost);
            return(state with
            {
                ClientPosts = posts
            });
        }
 public bool ChangeState(PostState NewState)
 {
     if (NewState != ExpectedState)
     {
         ExpectedState = NewState;
         FilterItemSource();
         ScrollToTop(false);
         return(true);
     }
     return(false);
 }
        PostState GetNewState(PostState OldState)
        {
            switch (OldState)
            {
            case PostState.Unliked:
                return(PostState.Liked);

            default:
                return(PostState.Unliked);
            }
        }
Пример #12
0
        public void UpdatePostState(Post post, PostState state)
        {
            updatePostState.ExecuteNonQuery(new Dictionary <string, object>()
            {
                ["id"]    = post.id,
                ["state"] = state.ToString(),
            });

            post.state = state;

            TriggerCallbacks();
        }
Пример #13
0
        void DoPostponedReload(object state)
        {
            PostState postedState = (PostState)state;

            if (postedState.ShouldFailWithException)
            {
                FailUnderAspOrAnotherNonPostEnvironment();
            }
            else
            {
                Reload();
            }
        }
Пример #14
0
        public int CountAllPosts(PostState state)
        {
            var result = countPosts.ExecuteReader(new Dictionary <string, object>()
            {
                ["state"] = state.ToString(),
            });

            result.Read();
            int rv = (int)(long)result[0];

            result.Close();

            return(rv);
        }
Пример #15
0
        public static PostState GetPostsSuccess(PostState state, GetPostsSuccessAction action)
        {
            foreach (var post in action.ClientPosts)
            {
                if (state.ClientPosts.Any(x => x.Id == post.Id))
                {
                    continue;
                }

                state.ClientPosts.Add(post);
            }
            return(state with
            {
                ClientPosts = state.ClientPosts
            });
        }
Пример #16
0
    //post到远程服务器,并得到返回值
    private IEnumerator PostData(WWW www, PostState postState = PostState.Common)
    {
        yield return(www);

        Debug.Log(www.text);
        if (!string.IsNullOrEmpty(www.error) || www.text.Equals("false"))
        {
            //在控制台输出错误信息
            Debug.Log(www.error);
            ProcessFailed(postState);
            //将失败面板显示  上传中不显示;
        }
        else if (www.text.Substring(1, 9) == "\"code\": 0")
        {
            //如果成功,处理返回值
            switch (postState)
            {
            case PostState.SaveProgress:
                break;

            case PostState.LoadProgress:    //请求读档成功
                string loadString = www.text.Substring(www.text.IndexOf("\"data\":") + 9);
                loadString = loadString.Substring(0, loadString.Length - 2);
                Debug.Log("读档成功:" + loadString);
                break;

            case PostState.SubmitDataAndImage:   //请求传送数据和图片一次成功
                ProcessReturnValue(www.text);    //处理返回值
                break;

            case PostState.SubmitExperiment:                         //请求提交试验成功
                //saveAndLoadByJSON.SaveToWebByJson();
                Application.ExternalCall("SubmitExperimentSuccess"); //提交成功后,调用网上的函数
                Debug.Log("提交试验成功:");
                break;

            default:
                break;
            }
        }
        else
        {
            Debug.Log("服务器拒绝请求" + www.text);
            ProcessFailed(postState);
        }
    }
Пример #17
0
        void _List_InconsistencyDetected(object sender, ServerModeInconsistencyDetectedEventArgs e)
        {
            OnInconsistencyDetected(e);
            if (e.Handled)
            {
                return;
            }
            SynchronizationContext context = SynchronizationContext.Current;

            if (IsGoodContext(context))
            {
                PostState state = new PostState();
                state.ShouldFailWithException = true;
                context.Post(DoPostponedReload, state);
                state.ShouldFailWithException = false;
            }
            else
            {
                FailUnderAspOrAnotherNonPostEnvironment();
            }
        }
Пример #18
0
        public Gitlost_bot()
        {
            InitializeComponent();
            LoadFeedChannels();

            txtGitLostLog.ReadOnly     = true;
            btnStartGitLostBot.Enabled = true;
            btnStopGitLostBot.Enabled  = false;

            poststate = PostState.FirstBoot;
            lastPost  = null;

            gitlostHandler = new GitLostHandler();
            gitlostchecker = new GitLostTimedChecker(30000, NewPostFound_Tick);
            gitlostchecker.Start();

            btnStartGitLostBot.Click += (s, e) => StartGitLostBot();
            btnStopGitLostBot.Click  += (s, e) => StopGitLostBot();

            this.Load += (s, e) => StartGitLostBot();
        }
Пример #19
0
        private async void NewPostFound_Tick()
        {
            if (gitlostHandler.state == BotState.Running)
            {
                List <string[]> posts = await Task.Run(() => Fetcher.FetchTweets(1));

                if (posts.Count > 0)
                {
                    if (poststate == PostState.FirstBoot)
                    {
                        poststate = PostState.Ready;
                        lastPost  = posts[0];
                        await GitLostLog(new LogMessage(LogSeverity.Info, "Client", "Initial boot, latest tweet set as last post"));
                    }
                    else
                    {
                        if (posts[0][0] != lastPost[0])
                        {
                            lastPost = posts[0];
                            EmbedBuilder builder = new EmbedBuilder();

                            builder.WithTitle($"[Auto] Developers Swearing @gitlost • {lastPost[1]}")
                            .WithDescription(System.Net.WebUtility.HtmlDecode(lastPost[0]))
                            .WithColor(Discord.Color.Blue);

                            JsonHandler.channels.ForEach(async(c) =>
                            {
                                await(gitlostHandler._client.GetChannel(c) as ISocketMessageChannel).SendMessageAsync("", false, builder.Build());
                            });

                            await GitLostLog(new LogMessage(LogSeverity.Info, "Client", $"New post found, sended to {JsonHandler.channels.Count} channel(s)"));
                        }
                        else
                        {
                            await GitLostLog(new LogMessage(LogSeverity.Info, "Client", "No new post found"));
                        }
                    }
                }
            }
        }
Пример #20
0
        public void Handle(PostStartedEvent evnt)
        {
            var key = KeyUtils.GetStateKey(evnt.AggregateId);

            var state = _db.GetObject <BlogState>(key);

            if (state == null)
            {
                throw new Exception("Blog has to be started first.");
            }

            var bodyHtml      = TextUtils.GetHtmlFromMarkdown(evnt.Body);
            var bodyShortHtml = TextUtils.GetHtmlFromMarkdown(TextUtils.GetBodyShort(evnt.Body));

            var tags = evnt.Tags.Select(_ => new TagState
            {
                TagUrl   = _.Url,
                TagTitle = _.Title
            }).ToList();

            var post = new PostState
            {
                Url           = evnt.Url,
                Title         = evnt.Title,
                Body          = bodyHtml,
                BodyShort     = bodyShortHtml,
                PublishAt     = evnt.PublishAt,
                CategoryTitle = evnt.CategoryTitle,
                CategoryUrl   = evnt.CategoryUrl,
                Infobar       = evnt.Infobar,
                IsHidden      = evnt.Hidden,
                Tags          = tags
            };

            state.Posts.Add(post);

            _db.SetObject(key, state);
        }
Пример #21
0
        string PostStateToString(PostState state)
        {
            switch (state)
            {
            case PostState.Created:
                return("Created");

            case PostState.InBranchStock:
                return("In branch stock");

            case PostState.InDeliveryToBranchStock:
                return("In delivery to branch stock");

            case PostState.InDeviveryToPerson:
                return("In delivery to person");

            case PostState.Delivered:
                return("Delivered");

            default:
                return("- Unknown -");
            }
        }
Пример #22
0
 public static PostState SendCommentSuccess(PostState state, SendCommentSuccessAction action)
 {
     foreach (var post in state.ClientPosts)
     {
         if (action.NewComment.PostId.HasValue && action.NewComment.PostId == post.Id)
         {
             post.Comments.Insert(0, action.NewComment);
         }
         else
         {
             foreach (var comment in post.Comments)
             {
                 if (comment.Id == action.NewComment.CommentId)
                 {
                     comment.Replies.Insert(0, action.NewComment);
                 }
             }
         }
     }
     return(state with
     {
         ClientPosts = state.ClientPosts
     });
 }
Пример #23
0
        /// <summary>
        /// Method for updating state on a post.
        /// </summary>
        /// <param name="post">The post to update.</param>
        /// <param name="newState">The new state of the post.</param>
        /// <returns></returns>
        public Post Update(Post post, PostState newState)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }
            this.logger.WriteFormat("Update called on PostService, Id: {0}", post.Id);
            // Let's get the topic from the data-storage!
            Post oldPost = this.Read(post.Id);

            if (oldPost == null)
            {
                this.logger.WriteFormat("Update post failed, no post with the given id was found, Id: {0}", post.Id);
                throw new ArgumentException("post does not exist");
            }

            Post originalPost = oldPost.Clone() as Post;

            // Has state changed?
            if (oldPost.State != newState)
            {
                oldPost.State = newState;

                oldPost.Editor   = this.userProvider.CurrentUser;
                oldPost.EditorId = this.userProvider.CurrentUser.Id;
                oldPost.Changed  = DateTime.UtcNow;
                oldPost          = this.postRepo.Update(oldPost);
                this.logger.WriteFormat("Post updated in PostService, Id: {0}", oldPost.Id);
                this.eventPublisher.Publish <PostStateUpdated>(new PostStateUpdated(originalPost)
                {
                    UpdatedPost = oldPost
                });
                this.logger.WriteFormat("Update events in PostService fired, Id: {0}", oldPost.Id);
            }
            return(oldPost);
        }
Пример #24
0
		/// <summary>
		/// Method for updating state on a post.
		/// </summary>
		/// <param name="post">The post to update.</param>
		/// <param name="newState">The new state of the post.</param>
		/// <returns></returns>
		public Post Update(Post post, PostState newState) {
			if (post == null) {
				throw new ArgumentNullException("post");
			}
			this.logger.WriteFormat("Update called on PostService, Id: {0}", post.Id);
			// Let's get the topic from the data-storage!
			Post oldPost = this.Read(post.Id);
			if (oldPost == null) {
				this.logger.WriteFormat("Update post failed, no post with the given id was found, Id: {0}", post.Id);
				throw new ArgumentException("post does not exist");
			}

			Post originalPost = oldPost.Clone() as Post;
			// Has state changed?
			if (oldPost.State != newState) {
				oldPost.State = newState;

				oldPost.Editor = this.userProvider.CurrentUser;
				oldPost.EditorId = this.userProvider.CurrentUser.Id;
				oldPost.Changed = DateTime.UtcNow;
				oldPost = this.postRepo.Update(oldPost);
				this.logger.WriteFormat("Post updated in PostService, Id: {0}", oldPost.Id);
				this.eventPublisher.Publish<PostStateUpdated>(new PostStateUpdated(originalPost) {
					UpdatedPost = oldPost
				});
				this.logger.WriteFormat("Update events in PostService fired, Id: {0}", oldPost.Id);
			}
			return oldPost;
		}
Пример #25
0
 public void Remove(PostState PostState)
 {
     _context.PostStates.Remove(PostState);
     _context.SaveChanges();
 }
Пример #26
0
 public void Add(PostState PostState)
 {
     _context.PostStates.Add(PostState);
     _context.SaveChanges();
 }
Пример #27
0
 public void ObservableStateChange(PostState NewState) // Use this to invoke the collection/property changed event
 {
     State = NewState;
     NotifyPropertyChanged("State");
 }
Пример #28
0
 public void EndState()
 {
     PostState?.Invoke(this);
     FirstPulse = true;
 }
Пример #29
0
        public async Task <bool> CanUserSeePost(string userId, PostState post)
        {
            var postAuthorId = int.Parse(post.AuthorId);

            return(await CanUserInteract(userId, postAuthorId, post.ViewMyPostsAndComments, post.ViewAudiences));
        }
Пример #30
0
        public Post[] ReadAllPosts(PostState state, int limit, LimitBehavior limitBehavior)
        {
            var result = new List <Post>();

            SQLiteDataReader posts;

            if (limitBehavior == LimitBehavior.All)
            {
                posts = readPosts.ExecuteReader(new Dictionary <string, object>()
                {
                    ["state"] = state.ToString(),
                });
            }
            else if (limitBehavior == LimitBehavior.First)
            {
                posts = readPostsLimit.ExecuteReader(new Dictionary <string, object>()
                {
                    ["state"] = state.ToString(),
                    ["limit"] = limit.ToString(),
                });
            }
            else if (limitBehavior == LimitBehavior.Last)
            {
                posts = readPostsLimitReversed.ExecuteReader(new Dictionary <string, object>()
                {
                    ["state"] = state.ToString(),
                    ["limit"] = limit.ToString(),
                });
            }
            else
            {
                return(null);
            }

            while (posts.Read())
            {
                while (true)
                {
                    string id = posts.GetField <string>("id");

                    Post post   = null;
                    var  oldRef = activePosts.GetOrAdd(id, id =>
                    {
                        post = new Post();

                        // If post isn't null, we already have the right data
                        ReadPostFromReader(posts, post);

                        return(new WeakReference <Post>(post));
                    });

                    post ??= oldRef.TryGetTarget();

                    if (post != null)
                    {
                        // Success!
                        result.Add(post);
                        break;
                    }

                    // We didn't insert our object, but we also didn't get a valid object
                    // This suggests that we got a WeakReference without a valid pointer
                    // That's OK; (try to) remove it and try again.
                    activePosts.Remove(id, oldRef);
                }
            }
            posts.Close();

            return(result.ToArray());
        }
Пример #31
0
        public async Task <bool> CanUserCommentPost(int userId, PostState post)
        {
            var postAuthorId = int.Parse(post.AuthorId);

            return(await CanUserInteract(userId, postAuthorId, post.ReplyMyPostsAndComments, post.ReplyAudiences));
        }