Пример #1
0
        public ActionResult Edit(int id, PostVM fvm, HttpPostedFileBase file)
        {
            Post p = Service.GetById(id);

            p.Content = fvm.Content;
            if (file != null)
            {
                p.UrlImage = file.FileName;
            }
            else
            {
                p.UrlImage = p.UrlImage;
            }
            p.UrlVideo = "rien";
            p.PostDate = DateTime.Today;

            Service.Update(p);
            Service.Commit();
            //Service.Dispose();
            var fileName = "";

            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    fileName = Path.GetFileName(file.FileName);
                    var path = Path.
                               Combine(Server.MapPath("~/Content/Uploads/"),
                                       fileName);
                    file.SaveAs(path);
                }
            }

            return(RedirectToAction("Index"));
        }
Пример #2
0
        public async Task <PostVM> PublicDeatilPost(int id)
        {
            Post post = await _context.Posts.FindAsync(id);

            if (post == null)
            {
                return(null);
            }

            post = _context.Posts.Where(x => x.PostID == id).FirstOrDefault();

            var postVM = new PostVM()
            {
                PostID        = post.PostID,
                Title         = post.Title,
                DateCreated   = post.DateCreated,
                Caption       = post.Caption,
                Author        = post.Author,
                ImageFileName = Path.GetFileName(post.ImageFileName),
                Content       = post.Content,
                ListComments  = _comment_service.GetAllCommentByPostID(post.PostID)
            };

            return(postVM);
        }
Пример #3
0
        public async Task <IActionResult> AddOrEdit(int id = 0)
        {
            //var ids = GetUserInfo();
            PostVM postVM = new PostVM()
            {
                Post         = new Post(),
                CategoryList = _uniofWork.Category.GetSelectListAsync()
            };

            if (id == 0)
            {
                return(View(postVM));
            }
            else
            {
                postVM.Post = await _uniofWork.Post.GetByIdAsync(id);
            }

            // access to edit have admin, moderator and post author
            bool result = AccessRights.AuthorAdminAccessRight(HttpContext, postVM.Post.ApplicationUserId, _db);

            if (result)
            {
                return(View(postVM));
            }
            return(new RedirectResult("~/Identity/Account/AccessDenied"));
        }
        //AFFICHAGE DE TOUS LES POSTS
        public ActionResult Index()
        {
            List <PostDTO>    Lesposts         = db.AllPost();
            List <int>        Liste_post_ID    = (from r in Lesposts select r.PostID).ToList();
            List <CommentDTO> LesCommentaires  = db.ListeCommentaire(Liste_post_ID);
            List <PostVM>     All_Post_Comment = new List <PostVM>();

            foreach (var item in Lesposts)
            {
                PostVM temp = new PostVM();
                temp.PostID  = item.PostID;
                temp.nom     = item.nom;
                temp.prenom  = item.prenom;
                temp.content = item.content;

                temp.date_create = item.date_create;
                temp.Comments    = LesCommentaires.Where(c => c.PostID == temp.PostID).ToList();
                All_Post_Comment.Add(temp);
            }

            if (Session["Nom"] == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            else
            {
                return(View(All_Post_Comment));
            }
        }
Пример #5
0
        public IHttpActionResult AddPosts(PostVM PostVm)
        {
            try
            {
                if (PostVm.UserName != null)
                {
                    var user = Context.User.Where(u => u.Name == PostVm.UserName).FirstOrDefault();

                    Posts newpost = new Posts()
                    {
                        Title       = PostVm.Title,
                        Describtion = PostVm.Description,
                        PostTime    = DateTime.Now.Date,
                        CategoryID  = PostVm.CategoryID,
                        UserID      = user.ID,
                    };

                    Context.Post.Add(newpost);
                    Context.SaveChanges();
                    //Context.Database.ExecuteSqlCommand("insert into [dbo].[Posts] ([Title],[Describtion],[PostTime],[UserID],[CategoryID]) values({0},{1},{2}, {3}, {4})",newpost.Title,newpost.Describtion,newpost.PostTime,newpost.UserID,newpost.CategoryID);
                }
                string location = "http://localhost:60201/api/Post";

                return(Created(location, "Post Saved"));
            }
            catch (Exception e)
            {
                throw e;
                // return BadRequest(e.Message);
            }
        }
        //VOIR MES POSTS
        public ActionResult MesPosts()
        {
            if (Session["Nom"] == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            else
            {
                List <PostDTO>    Lesposts         = db.postByUserID((int)Session["ID"]);
                List <int>        Liste_post_ID    = (from r in Lesposts select r.PostID).ToList();
                List <CommentDTO> LesCommentaires  = db.ListeCommentaire(Liste_post_ID);
                List <PostVM>     All_Post_Comment = new List <PostVM>();

                foreach (var item in Lesposts)
                {
                    PostVM temp = new PostVM();
                    temp.PostID  = item.PostID;
                    temp.nom     = item.nom;
                    temp.prenom  = item.prenom;
                    temp.content = item.content;

                    temp.date_create = item.date_create;
                    temp.Comments    = LesCommentaires.Where(c => c.PostID == temp.PostID).ToList();

                    All_Post_Comment.Add(temp);
                }
                System.Diagnostics.Debug.WriteLine("ID USER" + LesCommentaires);
                return(View(All_Post_Comment));
            }
        }
Пример #7
0
        public ActionResult WritePost()
        {
            PostVM vm = new PostVM();

            vm.HashTags = rules.GetAllTags();
            return(View(vm));
        }
Пример #8
0
        // GET: Posts/Edit/5
        public async Task <IActionResult> Edit(uint?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var post = await _context.Posts.Include(p => p.PostTags).Where(p => p.Id == id).FirstOrDefaultAsync();

            if (post == null)
            {
                return(NotFound());
            }
            ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name", post.CategoryId);
            ViewData["UserId"]     = new SelectList(_context.Users, "Id", "Email", post.UserId);

            _logger.LogInformation("test post {0} {1}", post.PostTags, post.Title);

            var viewModel = new PostVM
            {
                Post         = post,
                TagsList     = new SelectList(_context.Tags, "Id", "Name"),
                SelectedTags = post.PostTags.Select(pt => pt.TagId)
            };

            return(View(viewModel));
        }
Пример #9
0
        public IActionResult RequestPost(int postId)
        {
            ApplicationUserVM user = _accountService.GetByUserName(User.Identity.Name);
            PostVM            post = _postService.GetAll().Find(x => x.Id == postId);

            if (post != null && user.Points >= post.Subcategory.Points)
            {
                IEnumerable <OrderVM> orders = _orderService.GetAll().Where(x => x.PostId == postId && x.UserId == user.Id);//db.Orders.Where(i => i.PostId == postId).ToList().Where(i => i.UserId == userId).ToList(); //all orders from this postid and userid
                if (orders.Count() == 0)
                {
                    _orderService.Create(new OrderVM
                    {
                        PostId = postId,
                        UserId = user.Id,
                        Post   = _postService.GetAll().FirstOrDefault(x => x.Id == postId),
                        User   = _accountService.GetById(user.Id)
                    });
                }
                else
                {
                    TempData["Message"] = "Вы не можете запросить повторно один и тот же пост";
                }
            }
            else
            {
                TempData["Message"] = "У вас недостаточно бонусов";
            }

            return(RedirectToAction("RequestPost"));
        }
Пример #10
0
        public ActionResult CreatePost(PostVM model, HttpPostedFileBase upload)
        {
            var mgr        = new PostManager();
            var catManager = new CategoryManager();
            var post       = new Post();

            var filePath = "~/images/";

            filePath = Server.MapPath(filePath);
            upload.SaveAs(filePath + upload.FileName);

            post.PostImageFileName = (upload.FileName);
            post.PostTitle         = model.PostTitle;
            post.PostBody          = model.PostBody;
            post.PostCategory      = catManager.GetCategoryById(int.Parse(model.PostCategoryId)).Payload;
            post.PostTags          = new List <Tag>()
            {
                new Tag()
                {
                    TagName = "Test"
                }
            };

            var response = mgr.AddPost(post);

            if (response.Success == false)
            {
                throw new Exception();
            }

            model.ResetDropdown();
            return(View(model));
        }
Пример #11
0
        //записываем пост
        public string PostCreate(PostVM postVM, int user_id)
        {
            //мапим вюмодель в сущность
            var post = new Entity.Post()
            {
                Title   = postVM.Title,
                Content = postVM.Content,
                User_Id = user_id,
            };

            if (postRepository.PostCreate(post) == 0)
            {
                throw new AppException("Ошибка записи в блог");
            }

            //получаем крайний айди поста
            var postLastId = postRepository.PostGetLast();
            //получаем все тэги
            var allTags = postRepository.TagFindAll();

            foreach (var tag in postVM.Tags)
            {
                var tag_id   = allTags.FirstOrDefault(x => x.Title == tag.Title).Id;
                var post_tag = new Post_Tag()
                {
                    Post_Id = postLastId,
                    Tag_Id  = tag_id
                };
                //записываем тэги по посту
                postRepository.TagCreate(post_tag);
            }

            return("Запись успешно добавлена!");
        }
Пример #12
0
        /// <summary>
        /// Preview
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public async Task <JsonResult> OnPostPreviewAsync([FromBody] PostVM post)
        {
            // prep blog post
            List <Tag> tags = new List <Tag>();

            foreach (var title in post.Tags) // titles
            {
                tags.Add(await _tagSvc.GetByTitleAsync(title));
            }

            var blogPost = new BlogPost
            {
                User      = await _userManager.GetUserAsync(HttpContext.User),
                UserId    = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                Category  = await _catSvc.GetAsync(post.CategoryId),
                CreatedOn = GetCreatedOn(post.PostDate),
                Tags      = tags,
                Slug      = post.Slug.IsNullOrEmpty() ? "untitled" : post.Slug,
                Excerpt   = post.Excerpt,
                Title     = post.Title.IsNullOrEmpty() ? "Untitled" : post.Title,
                Body      = post.Body,
            };

            // prep TempData
            var prevRelLink = BlogRoutes.GetPostPreviewRelativeLink(blogPost.CreatedOn, blogPost.Slug);

            TempData.Put(prevRelLink, blogPost);

            // return preview url
            return(new JsonResult($"{Request.Scheme}://{Request.Host}{prevRelLink}"));
        }
Пример #13
0
        public ActionResult CreatePost()
        {
            var model = new PostVM();

            model.ResetDropdown();
            return(View(model));
        }
Пример #14
0
        public PostPage(Item item)
        {
            InitializeComponent();
            Xamarin.Forms.PlatformConfiguration.iOSSpecific.Page.SetUseSafeArea(this, true);

            ViewModel = Resources["vm"] as PostVM;
            ViewModel.SelectedPost = item;

            try
            {
                Title                 = item.Title;
                postImage.Source      = item.Enclosure.Url;
                creatorLabel.Text     = item.Creator;
                dateLabel.Text        = item.PublishedDate.ToString("MMMM dd");
                descriptionLabel.Text = item.Description;

                var properties = new Dictionary <string, string>
                {
                    { "Blog_Post", $"{item.Title}" }
                };

                TrackEvent(properties);
            }
            catch (Exception ex)
            {
                var properties = new Dictionary <string, string>
                {
                    { "Blog_Post", $"{item.Title}" }
                };
                TrackError(ex, properties);
            }
        }
Пример #15
0
        /// <summary>
        /// Ajax POST to publish a post.
        /// </summary>
        /// <returns>
        /// Absolute URL to the post.
        /// </returns>
        /// <remarks>
        /// The post could be new or previously published.
        /// </remarks>
        public async Task <JsonResult> OnPostPublishAsync([FromBody] PostVM post)
        {
            var blogPost = new BlogPost
            {
                UserId     = Convert.ToInt32(_userManager.GetUserId(HttpContext.User)),
                CategoryId = post.CategoryId,
                CreatedOn  = GetCreatedOn(post.PostDate),
                TagTitles  = post.Tags,
                Slug       = post.Slug,
                Excerpt    = post.Excerpt,
                Title      = post.Title,
                Body       = post.Body,
                Status     = EPostStatus.Published,
            };

            if (post.Id <= 0)
            {
                blogPost = await _blogSvc.CreateAsync(blogPost);
            }
            else
            {
                blogPost.Id = post.Id;
                blogPost    = await _blogSvc.UpdateAsync(blogPost);
            }

            return(new JsonResult(GetPostAbsoluteUrl(blogPost)));
        }
Пример #16
0
        public ActionResult DeletePost(int Id)
        {
            PostVM post = _postService.GetAll().FirstOrDefault(x => x.Id == Id);

            if (post != null)
            {
                _postService.Remove(Id);
                List <ImagesGalleryVM> images = _imageGalleryService.Find(Id).ToList();
                if (images.Count == 1)
                {
                    _imageGalleryService.RemoveItem(images[0]);
                }
                else
                {
                    _imageGalleryService.RemoveRange(images);
                }

                List <OrderVM> orders = _orderService.GetAll().Where(x => x.PostId == Id).ToList();
                if (orders.Count > 0)
                {
                    _orderService.RemoveRange(orders);
                }

                TempData["Message"] = "Пост был успешно удален";
            }
            else
            {
                TempData["Message"] = "Что-то пошло не так";
            }

            return(RedirectToAction("Posts"));
        }
        public JsonResult GetPostsOfRoom(string Room)
        {
            PostVM newpost;

            List <PostVM>  PostsList = new List <PostVM>();
            PostRepository postrepo  = new PostRepository();
            UserRepository userRepo  = new UserRepository();
            User           sender    = new User();
            var            posts     = postrepo.GetByRoom(Room);

            foreach (var post in posts)
            {
                sender           = userRepo.GetByEmail(post.Sender);
                newpost          = new PostVM();
                newpost.Id       = post.Id;
                newpost.PostText = post.PostText;
                newpost.Room     = post.Room;
                newpost.Sender   = sender.Username;
                newpost.DateTime = post.DateTime;
                newpost.Deleted  = post.Deleted;
                PostsList.Add(newpost);
            }

            return(Json(PostsList, JsonRequestBehavior.AllowGet));
        }
Пример #18
0
        public async Task <PostVM> Post(long id, long userId)
        {
            //var post=  await _manager._context.Posts.FindAsync(id);
            var p = await _manager._context.Posts.FindAsync(id);

            var comments = await _manager._context.Comments.Where(x => x.Post == p.Id).ToListAsync();

            var likes     = _manager._context.Likes.Count(x => x.Post == p.Id);
            var createdBy = await _manager._context.Users.FindAsync(p.CreatedBy);

            var postLikes = await _manager._context.Likes.Where(x => x.Post == p.Id).ToListAsync();

            var postVms = new PostVM
            {
                Id              = p.Id,
                Comments        = comments,
                CreateDate      = p.CreateDate,
                CreatedBy       = createdBy,
                MedicineNameAr  = p.MedicineNameAr,
                MedicineNameEng = p.MedicineNameEng,
                State           = p.State,
                Text            = p.Text,
                Likes           = likes,
                PostLikes       = postLikes,
                AllowComment    = (userId >= 1), PostType = p.PostType
            };

            return(postVms);
        }
Пример #19
0
        public ActionResult Create(PostVM data)
        {
            bool isSave = false;


            data.UserId      = User.Identity.GetUserId();
            data.PostEndDate = data.EndDate;
            if (data.questionId == 0 && data.PostId == 0)
            {
                data.CreationDate = DateTime.Now;
                isSave            = apiData.Post(data);
            }
            else
            {
                //isSave = apiData.Update(data);
            }
            if (isSave)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(Json(isSave, JsonRequestBehavior.AllowGet));
            }



            // return PartialView("_Create", data);
        }
Пример #20
0
        public IHttpActionResult PostTextMessage(PostVM <TextMessageStream> postModel)
        {
            StringBuilder traceLog = null;
            ServiceResponse <ViewPostVM> objResponse = null;

            try
            {
                traceLog = new StringBuilder();
                traceLog.AppendLine("Start: PostAndComment PostTextMessage() Request Data:-TargetId-" + postModel.TargetId + ",Stream-" + postModel.Stream + ",IsImageVideo-" + postModel.IsImageVideo);
                objResponse              = new ServiceResponse <ViewPostVM>();
                objResponse.jsonData     = PostAndCommentBL.PostShare(postModel);
                objResponse.IsResultTrue = true;
                return(Ok(objResponse));
            }
            catch (Exception ex)
            {
                LogManager.LogManagerInstance.WriteErrorLog(ex);
                return(BadRequest(ex.Message));
            }
            finally
            {
                traceLog.AppendLine("End: PostAndComment PostTextMessage() Response Result Status-" + objResponse.IsResultTrue + ",Posted DateTime-" + DateTime.Now.ToLongDateString());
                LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                traceLog = null;
            }
        }
Пример #21
0
        public ActionResult Edit(int id, PostVM fvm, int idP)
        {
            Post    post = Ser.GetById(idP);
            Comment p    = Service.GetById(id);


            p.Content     = fvm.Content;
            p.PostId      = idP;
            p.CommentDate = DateTime.Today;

            Service.Update(p);

            Service.Commit();

            /*foreach (Comment o in post.Comments)
             * {
             *  if (o.CommentId == id)
             *      post.Comments.Remove(o);
             * }*/
            //post.Comments.Add(p);
            //postt.Comments.Remove(postt.Comments.First(x=>x.CommentId==id));
            //postt.Comments.Add(p);
            //Ser.GetById(idP).Comments.Where(x=>x.CommentId==p.CommentId).up
            //postt.Comments = com;


            //Service.Dispose();
            //int a = (int)p.PostId;
            //Post post = Ser.GetById(idP);
            //post.Comments.Add(p);

            return(Redirect("~/Post/Details/" + idP));
        }
Пример #22
0
        public IEnumerable <PostVM> postAll()
        {
            var postAll = new List <PostVM>();

            foreach (var post in postRepository.PostFindAll())
            {
                var tagsVM = new List <TagVM>();

                //получаем список пост_блог
                var tags = postRepository.PostTagFindByID(post);

                foreach (var tag in tags)
                {
                    var tagVM = new TagVM()
                    {
                        Title = postRepository.TagFindById(tag.Tag_Id).Title
                    };
                    tagsVM.Add(tagVM);
                }

                var postVM = new PostVM()
                {
                    Title   = post.Title,
                    Content = post.Content,
                    Tags    = tagsVM
                };
                postAll.Add(postVM);
            }
            return(postAll);
        }
Пример #23
0
        public PostPage()
        {
            InitializeComponent();
            Xamarin.Forms.PlatformConfiguration.iOSSpecific.Page.SetUseSafeArea(this, true);

            ViewModel = Resources["vm"] as PostVM;
        }
Пример #24
0
        public PartialViewResult Footer()
        {
            PostVM VM = new PostVM();

            VM.categories = db.tbl_category.Take(6).ToList();
            VM.postList   = db.tbl_post.Take(3).ToList();
            return(PartialView(VM));
        }
Пример #25
0
        public ActionResult EditStaticPost(PostVM postVM)
        {
            BlogManager manager = BlogManagerFactory.Create();

            manager.UpdateStaticPost(postVM.Post);

            return(RedirectToAction("ViewStaticPosts"));
        }
Пример #26
0
        public ActionResult DeleteStaticPost(PostVM postVM)
        {
            BlogManager manager = BlogManagerFactory.Create();

            manager.DeleteStaticPost(postVM.Post.StaticPostId);

            return(RedirectToAction("ViewStaticPosts"));
        }
Пример #27
0
        public ActionResult CreateStaticPost()
        {
            BlogManager manager = BlogManagerFactory.Create();

            var postVM = new PostVM();

            return(View(postVM));
        }
Пример #28
0
        public ActionResult CreateStaticPost(PostVM model)
        {
            BlogManager manager = BlogManagerFactory.Create();

            manager.AddPost(model.Post);

            return(RedirectToAction("ViewStaticPosts"));
        }
Пример #29
0
        public PartialViewResult RelatedCategory(int id)
        {
            PostVM VM = new PostVM();

            VM.postList = db.tbl_post.Where(x => x.CategoryId == id).Take(6).ToList();

            return(PartialView(VM));
        }
 public ActionResult NewPost(PostVM postVM)
 {
     if (!ModelState.IsValid)
     {
         return(View("NewPost"));
     }
     return(View());
 }