示例#1
0
        public ActionResult PostStatus(FormCollection collection)
        {/*
          * post.HtmlText = Helpers.ParseText(post.Text);
          * post.FromUserId = User.Identity.GetUserId();
          * post.PosterName = _userService.GetFullNameById(User.Identity.GetUserId());
          * _postService.AddPost(post);
          * InteractionBarViewModel model = new InteractionBarViewModel();
          * model.IsPost = true;
          * model.Feed.Add(post);
          * model.Post = post;
          * var postHtml = Helpers.RenderViewToString(this.ControllerContext, "PostPartial", model);
          * return Json(postHtml, JsonRequestBehavior.AllowGet);
          */
            Post   post = new Post();
            string text = collection["status"];

            if (String.IsNullOrEmpty(text))
            {
                return(RedirectToAction("Profile", "User", new { userId = post.ToUserId }));
            }
            post.Text       = text;
            post.HtmlText   = Helpers.ParseText(text);
            post.FromUserId = User.Identity.GetUserId();
            post.ToUserId   = collection["toUserId"];
            post.PosterName = _userService.GetFullNameById(User.Identity.GetUserId());
            if (post.FromUserId != null)
            {
                _postService.AddPost(post);
                return(RedirectToAction("Profile", "User", new { userId = post.ToUserId }));
            }

            return(View("Error"));
        }
示例#2
0
        public ActionResult Create([Bind(Include = "Model.Content")] HomeIndexViewModel viewModel)
        {
            Post parentPost = null;

            if (Request.Form.Get("postModel.parentPost") != null)
            {
                var parentPostId = Request.Form.Get("postModel.ParentPost");
                parentPost = _postService.GetPost(new Guid(parentPostId));
            }
            var    content = Request.Form.Get("postModel.Content");
            string url     = null;

            if (Request.Form.Get("lpid") != null)
            {
                var lpid = new Guid(Request.Form.Get("lpid"));

                var link = _linkPreviewService.FindLinkPreviewById(lpid);
                content = link.Url;
                url     = link.Url;
            }

            var userId             = User.Identity.GetUserId();
            var currentUserProfile = _userProfileService.GetUserProfileByUserId(new Guid(userId));

            _postService.AddPost(currentUserProfile, content, parentPost, url);
            return(RedirectToAction("Index", "Home"));
        }
示例#3
0
        public ActionResult CreatePost(PostViewModel s, int Id)
        {
            if (ModelState.IsValid)
            {
                var userService  = new UserService(myDbContext);
                var groupService = new GroupService(myDbContext);
                var postService  = new PostService(myDbContext);
                var group        = groupService.GetGroup(Id);

                Post p = new Post();

                p.PostText         = s.PostText;
                p.PostTime         = DateTime.Now;
                p.GroupId          = group;
                p.UserAnonymous    = s.UserAnonymous;
                p.User             = userService.GetUser(User.Identity.GetUserId());
                p.StatusOrQuestion = s.StatusOrQuestion;

                postService.AddPost(p);

                return(RedirectToAction("detail", new { id = Id }));
            }
            else
            {
                return(View(s));
            }
        }
        private static void AddPost()
        {
            postservice.PostAdded += Postservice_PostAdded;

            Console.WriteLine("Enter your username:"******"Please enter your message:");
                postservice.AddPost(username, Console.ReadLine(), DateTime.Now);
            }
            else
            {
                Console.WriteLine("\nPlease Register First!");

                ConsoleKeyInfo c;
                do
                {
                    Console.Write("\nPress Enter to go to menu!");
                    c = Console.ReadKey();
                } while (c.Key != ConsoleKey.Enter);
            }
        }
        public async System.Threading.Tasks.Task <ActionResult> Create(Topic topic, string message, int forumID)
        {
            StringBuilder sbBody = new StringBuilder();

            sbBody.Append(HttpUtility.HtmlEncode(message));

            message = sbBody.ToString();
            message = message.Replace(Environment.NewLine, "<br />");

            user = fum.GetCurrentForumUser(User.Identity.GetUserId());
            string ip = Request.UserHostAddress;

            this.topic = await ts.AddTopic(topic, forumID, user);

            if (this.topic != null)
            {
                this.post = await ps.AddPost(this.topic.Title, message, ip, this.topic.Id, user);

                if (this.post != null)
                {
                    await fs.UpdateForumCountByForumID(forumID, this.topic.Id, this.post.Id, user, ForumCountUtilities.TOPIC);

                    return(RedirectToAction("ViewForum", "Forum", new { id = forumID }));
                }
            }
            return(RedirectToAction("Create", forumID));
        }
示例#6
0
        public async Task <IActionResult> AddPost([FromBody] PostModel postModel)
        {
            var user = await _userService.GetOneByEmail(User.Identity.Name);

            await _postService.AddPost(postModel, user);

            return(Ok(new { message = "Post adicionado com sucesso." }));
        }
        public void PostService_AddPost_PostCorrect_Post()
        {
            var expected = new Post.Post("Alice", "Alice Message", DateTime.Parse("01/01/2018"));

            var result = postService.AddPost("Alice", "Alice Message", DateTime.Parse("01/01/2018"));

            Assert.AreEqual(expected, result);
        }
        public async Task <IActionResult> AddPost(string title, string content)
        {
            var user = _userService.GetByEmail(User.Identity.Name).Result;

            _postService.AddPost(content, title, user.UserName);
            var posts = _postService.GetAllByProfile(user).ToList();

            return(View("_Posts", posts));
        }
示例#9
0
        public JsonResult AddPost(PostViewModel post)
        {
            bool isSaved = false;

            if (ModelState.IsValid)
            {
                if (post.Tags != null && post.Tags.Count > 0)
                {
                    var tags = _postService.Tags();
                    foreach (var tag in post.Tags)
                    {
                        var _result = tags.Where(x => x.Tag.ToLower() == tag.Tag.ToLower()).FirstOrDefault();
                        if (_result != null)                         //exsiting tag
                        {
                            tag.TagId = _result.TagId;
                        }
                        else                         //new tag
                        {
                            tag.TagId = 0;
                        }
                    }
                    isSaved = _postService.AddPost(post);
                }
                else
                {
                    isSaved = _postService.AddPost(post);
                }
            }
            else
            {
                /*
                 * foreach (ModelState modelState in ViewData.ModelState.Values)
                 * {
                 *      foreach (ModelError error in modelState.Errors)
                 *      {
                 *              var info = error.ErrorMessage;
                 *      }
                 * }
                 */
                isSaved = false;
            }
            return(Json(isSaved));
        }
示例#10
0
    protected void btnPublicar_Click(object sender, EventArgs e)
    {
        var post = new Post();

        post.title   = this.tbTitle.Text;
        post.review  = tbReview.Text;
        post.content = tbContenido.Text;

        PostService.AddPost(post);
        Response.Redirect("http://localhost:52594/Forms/NewsInForm.aspx");
    }
示例#11
0
        public void AddPost_NullPost_FalseFlag()
        {
            Mock<IRepository<Post>> repository = new Mock<IRepository<Post>>();
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            Mock<IMediaService> mediaService = new Mock<IMediaService>();
            Mock<IFileService> fileService = new Mock<IFileService>();

            PostService service = new PostService(repository.Object, loggerService.Object, mediaService.Object, fileService.Object);
            bool flag = service.AddPost(null);
            Assert.IsFalse(flag);
        }
示例#12
0
        public IActionResult AddPost(string newTitle, string newBody, long sectionId)
        {
            if (newBody is null)
            {
                newBody = string.Empty;
            }
            postService.AddPost(newTitle, newBody, sectionId);

            return(Json(new {
                flag = true
            }));
        }
示例#13
0
        private void AddPost(object sender, RoutedEventArgs e)
        {
            Post newPost = _postService.AddPost(Constant.DefaultTitle, string.Empty);

            if (newPost == null)
            {
                return;
            }

            PostList.Add(newPost);
            TitleList.SelectedValue = PostList.Last();
            _currentPost            = newPost;
        }
示例#14
0
        public async Task <ActionResult <PostViewModel> > CreatePost(PostInputViewModel viewModel)      // null reference happening with viewModel
        {
            if (viewModel == null)
            {
                return(BadRequest());
            }

            Post createdPost = await PostService.AddPost(Mapper.Map <Post>(viewModel));

            return(CreatedAtAction(nameof(Get_PostId),
                                   new { id = createdPost.Id },
                                   Mapper.Map <PostViewModel>(createdPost)));
        }
示例#15
0
        public ActionResult PostOnGroup(FormCollection collection)
        {
            Post   post = new Post();
            string text = collection["status"];

            if (String.IsNullOrEmpty(text))
            {
                return(RedirectToAction("Profile", "Group", new { groupId = post.GroupId }));
            }
            post.Text       = text;
            post.HtmlText   = Helpers.ParseText(text);
            post.FromUserId = User.Identity.GetUserId();
            post.GroupId    = Convert.ToInt32(collection["GroupId"]);
            post.PosterName = _userService.GetFullNameById(User.Identity.GetUserId());
            post.ToUserId   = null;           // Get ekki tekið út
            if (post.FromUserId != null)
            {
                _postService.AddPost(post);
                return(RedirectToAction("Profile", "Group", new { groupId = post.GroupId }));
            }

            return(View("Error"));
        }
示例#16
0
 private void CreatePost()
 {
     Field <GraphApi <PostResponse> >(
         "CreatePost",
         arguments: new QueryArguments(
             new QueryArgument <NonNullGraphType <GraphInputApi <Post> > > {
         Name = "post"
     }),
         resolve: context =>
     {
         var post = context.GetArgument <Post>("post");
         return(postService.AddPost(post));
     });
 }
示例#17
0
        public void ThenPostIsNotDisplayedOnMainPage(string isDisplayed)
        {
            Post post = PostBuilder.GeneratePost(RegistrationService.RegisterNewUser(AccountBuilder.CreateAccount()));

            PostService.AddPost(post);
            if (isDisplayed != "not")
            {
                Assert.IsTrue(PostService.IsPostDisplayed(post));
            }
            else
            {
                Assert.IsFalse(PostService.IsPostDisplayed(post));
            }
        }
示例#18
0
        public async Task <IActionResult> Index(HomeVm vm)
        {
            if (ModelState.IsValid)
            {
                ClaimsPrincipal currentUser   = this.User;
                var             currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
                var             post          = new Post();
                post.Description = vm.Description;
                post.UserId      = currentUserId;
                var UserName = postService.GetUserNameById(currentUserId);
                post.UserName = UserName;

                string uniqueFileName = null;
                if (vm.Image == null)
                {
                    postService.AddPost(post);
                }

                else if (postService.IsImage(vm.Image) && vm.Image.Length < (3 * 1024 * 1024))
                {
                    string uploadFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + vm.Image.FileName;
                    string filePath = Path.Combine(uploadFolder, uniqueFileName);

                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        vm.Image.CopyTo(fileStream);
                    }
                    post.ImagePath = uniqueFileName;
                    postService.AddPost(post);
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(RedirectToAction("Error", "Home", ""));
        }
示例#19
0
 public ActionResult CreatePost([Bind(Include =
                                          "Id,Title,Content,Visible,CategoryId,HeadImageBase64,Author,LiveTime,CommentsEnabled,ContentPreview")]
                                PostViewModel postViewModel)
 {
     if (!ModelState.IsValid || postViewModel.CategoryId == 0)
     {
         return(View(postViewModel));
     }
     _postService.AddPost(postViewModel);
     if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
     {
         return(RedirectToAction("PostsView"));
     }
     return(View("~/Views/Posts/Index.cshtml", _postService.GetPosts()));
 }
示例#20
0
        public async Task AddPostShouldStorePostOnDbAsync()
        {
            using (var context = new SocialNetworkDbContext(this._data.ContextOptions))
            {
                var postService = new PostService(context, null);

                var post = PostFakes.GetPost();

                await postService.AddPost(post);

                context.Posts.ToList()
                .Last()
                .Should()
                .BeEquivalentTo(post);
            }
        }
示例#21
0
        public void AddPost_GetPostDTOAndAddPostToReposistoryAndSaveChange()
        {
            //Arrange
            var uowMoq      = GetUowMoq();
            var postService = new PostService(uowMoq.Object);
            var newPostDTO  = new PostDTO()
            {
                Title = "test", Text = "test2"
            };

            //Act
            postService.AddPost(newPostDTO);

            //Assert
            uowMoq.Verify(m => m.Posts.Create(It.Is <Post>(p => p.Title == newPostDTO.Title &&
                                                           p.Text == newPostDTO.Text)));
            uowMoq.Verify(m => m.Save(), Times.Once());
        }
示例#22
0
        public ActionResult Post(PostModel post)
        {
            string id = Request.Headers["UserId"];

            JObject objResponse = _postService.AddPost(post, id);

            if (200 == (int)objResponse["status"])
            {
                return(new ObjectResult(objResponse));
            }
            else if (404 == (int)objResponse["status"])
            {
                return(new NotFoundObjectResult(objResponse));
            }
            else
            {
                return(new BadRequestObjectResult(objResponse));
            }
        }
示例#23
0
        public ActionResult PostPost(Post p)
        {
            Post   px       = p;
            string fileName = "";

            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                if (file != null && file.ContentLength > 0)
                {
                    fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(imgpath, fileName);
                    file.SaveAs(path);
                }
            }
            p.imagefname = fileName;
            PostService.AddPost(px, 1, imgpath);
            PostList = PostService.MakePostList(imgpath);
            return(View("PostViewing", PostList));
        }
        public async System.Threading.Tasks.Task <ActionResult> Create(Post post, string message, int mainPostID)
        {
            StringBuilder sbBody = new StringBuilder();

            sbBody.Append(HttpUtility.HtmlEncode(message));

            message = sbBody.ToString();
            message = message.Replace(Environment.NewLine, "<br />");

            Post   mainPost = ps.GetPostByID(mainPostID);
            string ip       = Request.UserHostAddress;

            user      = fum.GetCurrentForumUser(User.Identity.GetUserId());
            this.post = await ps.AddPost(post.Subject, message, ip, mainPost.TopicId, user);

            if (this.post != null)
            {
                await fs.UpdateForumCountByForumID(mainPost.Topic.ForumId, mainPost.TopicId, post.Id, user, ForumCountUtilities.POST);

                ts.UpdateLastPostUsernameandDateByLastPost(this.post.TopicId, user.FirstName, DateTime.Now.ToString());
                return(RedirectToAction("ViewTopic", "Topic", new { id = mainPost.TopicId }));
            }
            return(View());
        }
示例#25
0
        public ActionResult Create(PostViewModel post)
        {
            if (ModelState.IsValid)
            {
                if (post.PostText != null)
                {
                    var userService = new UserService(myDbContext);
                    var postService = new PostService(myDbContext);

                    Post p = new Post();

                    p.PostText = post.PostText;
                    p.PostTime = DateTime.Now;
                    p.User     = userService.GetUser(User.Identity.GetUserId());
                    postService.AddPost(p);
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View(post));
            }
        }
示例#26
0
        static async Task SingleCaptureAndPost(PostService postService, PiCamService piCamService)
        {
            Guid     piPostID = Guid.NewGuid();
            DateTime nowTime  = DateTime.UtcNow;
            Post     piPost   = new Post
            {
                ID                   = piPostID,
                PostTitle            = $"Requested Image {DateTime.Now.ToShortDateString()} - {DateTime.Now.ToShortTimeString()}",
                PostDescription      = "Eventually this should be generated",
                IsActive             = true,
                IsLocked             = false,
                StartTimeUTC         = nowTime,
                LockTimeUTC          = nowTime,
                EndTimeUTC           = nowTime,
                CreatedUTC           = nowTime,
                LastUpdatedUTC       = nowTime,
                SiteAccountID        = SiteRobsRaspID,
                UserAccountCreatorID = UserBudNJoeID
            };

            Console.WriteLine($"Single Image Capture Requested. {piPostID}");

            var testConnection = await postService.TestConnection();

            if (!testConnection.Success)
            {
                await piCamService.UpdateProgress("Error connecting :(", -1, STEP_COUNT);

                Console.WriteLine("Connection Error!");
                return;
            }

            await piCamService.UpdateProgress("Received", 1, STEP_COUNT);

            PiCapture piCam = new PiCapture();

            if (!piCam.TryOpenVideoCapture())
            {
                await piCamService.UpdateProgress("Opening Camera", 2, STEP_COUNT);

                piCam.ForceOpenVideoCapture();
            }
            await piCamService.UpdateProgress("Capturing", 3, STEP_COUNT);

            byte[] imageBytes = piCam.SingleImageCameraByteArray();

            await piCamService.UpdateProgress("Uploading Image", 4, STEP_COUNT);

            piPost.PostImageUri = await CloudUpload.UploadPostImage(piPostID, imageBytes);

            await piCamService.UpdateProgress("Creating Post", 5, STEP_COUNT);

            var savePostResponse = await postService.AddPost(piPost);

            if (savePostResponse.Success)
            {
                await piCamService.UpdateProgress("Success!", 6, STEP_COUNT);

                Console.WriteLine("Completed Successfully! A New Post Should Be Availible.");
            }
            else
            {
                await piCamService.UpdateProgress("Error saving post :(", -1, 6);

                Console.WriteLine($"An Error happened while saving the post: {savePostResponse.Error.Message}");
            }
            piCam.DisposeCaptureInstance();
        }
 public void Post([FromBody] PostModel newPost)
 {
     _postService.AddPost(newPost);
 }
示例#28
0
 public Boolean AddPost([FromBody] PostDto postModel)
 {
     return(postService.AddPost(postModel));
 }
        public ActionResult SaveUploadedFile()
        {
            var fName = "";

            try
            {
                foreach (string fileName in Request.Files)
                {
                    var file = Request.Files[fileName];
                    //Save file content goes here
                    if (file != null && file.ContentLength > 0)
                    {
                        fName = file.FileName;
                        var originalDirectory =
                            new DirectoryInfo(string.Format($"{0}Content\\galleries", Server.MapPath(@"\")));
                        var userId             = User.Identity.GetUserId();
                        var currentUserProfile = _userProfileService.GetUserProfileByUserId(new Guid(userId));
                        if (currentUserProfile != null)
                        {
                            var pathString = Path.Combine(originalDirectory.ToString(), userId);
                            var isExists   = Directory.Exists(pathString);
                            if (!isExists)
                            {
                                Directory.CreateDirectory(pathString);
                            }
                            var path = string.Format($"{0}\\{1}", pathString, file.FileName);
                            file.SaveAs(path);
                            var post = new Post
                            {
                                Content       = "descriere", //TODO add content to photo
                                UserProfile   = currentUserProfile,
                                UserProfileId = currentUserProfile.Id,
                                PostDateTime  = DateTime.Now,
                                Id            = Guid.NewGuid(),
                                PhotoLink     = path.Replace("E:\\Visual Studio Projects\\social-network\\WebApplication4",
                                                             "../../")
                            };
                            try
                            {
                                _postService.AddPost(currentUserProfile, "descriere", null, null, path.Replace(
                                                         "E:\\Visual Studio Projects\\social-network\\WebApplication4",
                                                         "../../"));
                            }
                            catch (DbEntityValidationException e)
                            {
                                foreach (var exception in e.EntityValidationErrors)
                                {
                                    System.Diagnostics.Debug.WriteLine(exception.ValidationErrors.ToString());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new { ex.Message }));
            }

            return(Json(new { Message = fName }));
        }
 public PostDTO Post([FromBody] Post post)
 {
     return(_postService.AddPost(post));
 }
示例#31
0
        public void AddPost_ValidPost_TrueFlag()
        {
            Post post = new Post();
            post.ID = Guid.NewGuid();
            post.PostData = "data";

            Mock<IRepository<Post>> repository = new Mock<IRepository<Post>>();
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            Mock<IMediaService> mediaService = new Mock<IMediaService>();
            Mock<IFileService> fileService = new Mock<IFileService>();

            repository.Setup(o => o.Insert(post));

            PostService service = new PostService(repository.Object, loggerService.Object, mediaService.Object, fileService.Object);
            bool flag = service.AddPost(post);

            Assert.IsTrue(flag);
        }
示例#32
0
 public void GivenThereIsSomePost()
 {
     PostService.AddPost(PostBuilder.GeneratePost(LoginService.Login(RegistrationService.RegisterNewUser(AccountBuilder.CreateAccount()))));
 }