Пример #1
0
        public async Task <IActionResult> Show(int id, int page = 1)
        {
            int   pageSize = 4;
            Topic topic;

            try {
                topic = _db.Topics.First(t => t.Id == id);
            }
            catch (Exception _)
            {
                return(StatusCode(404));
            }
            _db.Entry(topic).Reference(t => t.User).Load();
            var count = await _db.Messages.CountAsync(msg => msg.TopicId == id);

            topic.Messages = await _db.Messages.Where(msg => msg.TopicId == id).Skip((page - 1) * pageSize).Take(pageSize).ToListAsync();

            foreach (var msg in topic.Messages)
            {
                _db.Entry(msg).Reference(m => m.User).Load();
            }
            PageViewModel pageViewModel = new PageViewModel(count, page, pageSize);

            return(View(new TopicShowViewModel()
            {
                Topic = topic,
                Id = topic.Id,
                PageViewModel = pageViewModel
            }));
        }
Пример #2
0
 public ActionResult ChangePassword(ChangePasswordModel model)
 {
     if (ModelState.IsValid)
     {
         User user = db.Users.FirstOrDefault(p => p.Id == model.UserId);
         if (user != null)
         {
             // Если введенный старый пароль совпадает с паролем в БД
             if (user.Password == LoginHelper.GetHash(model.PasswordOld))
             {
                 // Изменяем пароль
                 user.Password        = LoginHelper.GetHash(model.Password);
                 db.Entry(user).State = EntityState.Modified;
                 db.SaveChanges();
                 return(RedirectToAction("Profile/" + user.Login, "Account"));
             }
             // иначе добавляем сообщение об ошибке
             else
             {
                 ModelState.AddModelError("", "Неверный старый пароль!");
             }
         }
         else
         {
             ModelState.AddModelError("", "Ошибка при изменении пароля...");
         }
     }
     return(View(model));
 }
Пример #3
0
        public void EditDiscussion(Discussion u)
        {
            ForumContext db = new ForumContext();

            db.Entry(db.discussionDB.SingleOrDefault(x => x.DiscussionId == u.DiscussionId)).CurrentValues.SetValues(u);
            db.SaveChanges();
        }
Пример #4
0
        public void EditPost(Post u)
        {
            ForumContext db = new ForumContext();

            db.Entry(db.postDB.SingleOrDefault(x => x.id == u.id)).CurrentValues.SetValues(u);
            db.SaveChanges();
        }
Пример #5
0
        public async Task <IActionResult> PutPost([FromRoute] int id, [FromBody] Post post)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != post.Id)
            {
                return(BadRequest());
            }

            _context.Entry(post).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #6
0
        internal SubjectResp AddSubjectAction(SubjectData subject, int c_id, int t_id)
        {
            using (var db = new ForumContext())
            {
                Forum category;
                category = (from e in db.Forum where e.CategoryID == c_id select e).Include(d => d.Topics).FirstOrDefault();

                FTopic topic;
                topic = (from e in category.Topics where e.TopicID == t_id select e).FirstOrDefault();

                if (topic.Subjects == null)
                {
                    topic.Subjects = new List <FSubject>();
                }
                var sub = new FSubject()
                {
                    Title = subject.Title,
                    Text  = subject.Text
                };

                topic.Subjects.Add(sub);
                db.Entry(category).State = EntityState.Modified;
                db.SaveChanges();
            }

            return(new SubjectResp());
        }
Пример #7
0
        public async Task Remove(int id)
        {
            TEntity entityToDelete = await _dbSet.FindAsync(id);

            if (entityToDelete == null)
            {
                throw new ArgumentException($"There is no such {typeof(TEntity)}");
            }

            if (_context.Entry(entityToDelete).State == EntityState.Detached)
            {
                _dbSet.Attach(entityToDelete);
            }

            _dbSet.Remove(entityToDelete);
        }
        // PUT api/Users/5
        public HttpResponseMessage PutUser(int id, User user)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != user.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            db.Entry(user).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #9
0
 public ActionResult Edit(Rubric model)
 {
     // Если модель валидна
     if (ModelState.IsValid)
     {
         // Получаем запись раздела из БД
         Rubric rubric = db.Rubrics.FirstOrDefault(p => p.Id == model.Id);
         // Если такая запись есть
         if (rubric != null)
         {
             // изменяем ее и сохраняем в БД
             rubric.Name            = model.Name;
             db.Entry(rubric).State = EntityState.Modified;
             db.SaveChanges();
             // редирект к списку разделов
             return(RedirectToAction("Index"));
         }
         // иначе добавляем сообщение об ошибке
         else
         {
             ModelState.AddModelError("", "Ошибка при сохранении");
         }
     }
     return(View(model));
 }
Пример #10
0
 public ActionResult EditTopic(Topic topic, string IsMessagingStr)
 {
     topic.IsMessaging     = IsMessagingStr == "true" ? true : false;
     db.Entry(topic).State = EntityState.Modified;
     db.SaveChanges();
     return(RedirectToAction("Topic", "Home", new { id = topic.Id }));
 }
Пример #11
0
 public IActionResult Index()
 {
     return(View(_db.Topics.OrderByDescending(topic => topic.MessageCount).Select(delegate(Topic topic)
     {
         _db.Entry(topic).Reference(t => t.User).Load();
         return topic;
     })));
 }
Пример #12
0
        public async Task <ActionResult> Edit(Post post)
        {
            post.UpdateDate      = DateTime.Now;
            db.Entry(post).State = System.Data.Entity.EntityState.Modified;
            await db.SaveChangesAsync();

            return(RedirectToAction($"Posts/{post.ThemeId}", "Home"));
        }
Пример #13
0
        public ActionResult Edit(Post p)
        {
            ForumContext context = new ForumContext();

            //context.post.Find(p.postId);
            context.Entry(p).State = EntityState.Modified;
            context.SaveChanges();
            return(RedirectToAction("Details", "Thread", new { id = p.ThreadID }));
        }
Пример #14
0
        public async Task <IEnumerable <Topic> > GetAllTopicsAsync()
        {
            IEnumerable <Topic> topics = await _repository.GetAllAsync();

            topics.ToList().ForEach(topic =>
            {
                _forumContext.Entry(topic).Collection(topic => topic.Posts).Load();

                var posts = topic.Posts.ToList();
                posts.Sort((a, b) => a.TimePublished.CompareTo(b.TimePublished));

                _forumContext.Entry(posts.First()).Reference(post => post.Author).Load();
            });

            _logger.LogDebug($"Got topics: {topics}");

            return(topics);
        }
Пример #15
0
 public ActionResult Edit([Bind(Include = "ID,ForumThreadID,Text,PublishDate,Author")] ForumPost forumPost)
 {
     if (ModelState.IsValid)
     {
         db.Entry(forumPost).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Details", "ForumThreads", new { id = forumPost.ForumThreadID }));
     }
     return(View(forumPost));
 }
        public ActionResult DeleteMessage(int messageId)
        {
            //Доробити перевірку
            var message = db.Messages.Include(n => n.MessageFiles).FirstOrDefault(n => n.Id == messageId);

            if (message != null)
            {
                int count = message.MessageFiles.Count;
                while (count > 0)
                {
                    db.Entry(message.MessageFiles.First()).State = EntityState.Deleted;
                    count = message.MessageFiles.Count;
                }
                db.SaveChanges();
                db.Entry(message).State = System.Data.Entity.EntityState.Deleted;
                db.SaveChanges();
            }
            return(RedirectToAction("Topic", "Home", new { id = message.TopicId }));
        }
Пример #17
0
        public ActionResult UnlockThread(int id)
        {
            ForumContext context = new ForumContext();
            Thread       thread  = context.thread.Where(s => s.id == id).FirstOrDefault();

            thread.status = "Unlocked";
            context.Entry(thread).State = EntityState.Modified;
            context.SaveChanges();
            return(RedirectToAction("Details", "Thread", new { id = id }));
        }
Пример #18
0
 public ActionResult Edit([Bind(Include = "id,username,pass,AboutMe,JoinedDate")] User user)
 {
     if (ModelState.IsValid)
     {
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     return(View(user));
 }
Пример #19
0
 public ActionResult Edit([Bind(Include = "DiscussionId,Posted,Title,Text,PosterId")] Discussion discussion)
 {
     if (ModelState.IsValid)
     {
         db.Entry(discussion).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     return(View(discussion));
 }
Пример #20
0
        public ActionResult EditDemote(int id)
        {
            ForumContext context = new ForumContext();
            User         u       = context.user.Where(s => s.userID == id).FirstOrDefault();

            u.userType             = "user";
            context.Entry(u).State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
            return(RedirectToAction("ViewUserList", "User"));
        }
 public ActionResult Edit([Bind(Include = "ID,Title,addedBy")] ForumSection forumSection)
 {
     if (ModelState.IsValid)
     {
         db.Entry(forumSection).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "ForumSections"));
     }
     return(View(forumSection));
 }
 public ActionResult Edit([Bind(Include = "IdKategorii,NazwaKategorii,OpisKategorii,IdIkony")] Kategoria kategoria)
 {
     if (ModelState.IsValid)
     {
         db.Entry(kategoria).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IdIkony = new SelectList(db.Ikony, "IdIkony", "NazwaIkony", kategoria.IdIkony);
     return(View(kategoria));
 }
Пример #23
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,Author,Topic,Body,Date,Post_id,Topic_id,Forum_id")] Forum_post forum_post)
        {
            if (ModelState.IsValid)
            {
                db.Entry(forum_post).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index", new { id = forum_post.Topic_id }));
            }
            return(null);
        }
Пример #24
0
        public async Task <IActionResult> PutTodoItem(long id, Subscribed_Rooms item)
        {
            if (id != item.Id)
            {
                return(BadRequest());
            }

            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
 public ActionResult Edit([Bind(Include = "IdPodKomentarza,Tresc,DataDodania,Id,IdKomentarza")] PodKomentarz podKomentarz)
 {
     if (ModelState.IsValid)
     {
         db.Entry(podKomentarz).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IdKomentarza = new SelectList(db.Komentarze, "IdKomentarza", "Tresc", podKomentarz.IdKomentarza);
     ViewBag.Id           = new SelectList(db.Users, "Id", "Email", podKomentarz.Id);
     return(View(podKomentarz));
 }
Пример #26
0
 public ActionResult Edit([Bind(Include = "IdKomentarza,Tresc,DataDodania,Id,IdTematu")] Komentarz komentarz)
 {
     if (ModelState.IsValid)
     {
         db.Entry(komentarz).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IdTematu = new SelectList(db.Tematy, "IdTematu", "Tytul", komentarz.IdTematu);
     ViewBag.Id       = new SelectList(db.Users, "Id", "Email", komentarz.Id);
     return(View(komentarz));
 }
Пример #27
0
 public ActionResult Edit([Bind(Include = "id,Text,Posted,DiscussionId,PosterId")] Post post)
 {
     if (ModelState.IsValid)
     {
         db.Entry(post).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", "Discussion"));
     }
     ViewBag.DiscussionId = new SelectList(db.discussionDB, "DiscussionId", "Title", post.DiscussionId);
     ViewBag.PosterId     = new SelectList(db.userDB, "id", "username", post.PosterId);
     return(View(post));
 }
Пример #28
0
        public async Task <IActionResult> Index(int topicId)
        {
            Topic?topic = await _topicService.GetTopicAsync(topicId);

            if (topic != null)
            {
                await _forumContext.Entry(topic).Collection(topic => topic.Posts).LoadAsync();

                topic.Posts.ToList().ForEach(post =>
                {
                    _forumContext.Entry(post).Reference(post => post.Author).Load();
                });

                await _topicService.IncrementViewCounter(topic);

                return(View(topic));
            }
            else
            {
                return(NotFound());
            }
        }
Пример #29
0
        public async Task <IActionResult> Show(string name)
        {
            User user = await _userManager.FindByNameAsync(name);

            if (user == null)
            {
                return(StatusCode(404));
            }
            User requester = await _userManager.FindByNameAsync(User.Identity.Name);

            if (name != User.Identity.Name)
            {
                user.DialogMessages = (from msg in _db.PrivateMessages
                                       where (msg.SenderId == user.Id && msg.ReceiverId == requester.Id) ||
                                       (msg.SenderId == requester.Id && msg.ReceiverId == user.Id)
                                       orderby msg.Published
                                       select msg).Select(delegate(PrivateMessage msg, int i)
                {
                    _db.Entry(msg).Reference(m => m.Sender).Load();
                    return(msg);
                }).ToList();
            }
            else
            {
                user.DialogMessages = _db.PrivateMessages.
                                      Where(msg => msg.SenderId == user.Id || msg.ReceiverId == user.Id).AsEnumerable().
                                      GroupBy(msg => msg.SenderId == user.Id ? msg.ReceiverId : msg.SenderId).
                                      Select(group => group.OrderByDescending(msg => msg.Published).First()).
                                      Select(delegate(PrivateMessage msg, int i)
                {
                    _db.Entry(msg).Reference(m => m.Sender).Load();
                    _db.Entry(msg).Reference(m => m.Receiver).Load();
                    return(msg);
                }).
                                      OrderByDescending(msg => msg.Published).ToList();
            }
            return(View(user));
        }
Пример #30
0
        public ActionResult Like(int id, int?userId)
        {
            ForumContext context = new ForumContext();
            Like         like    = new Like();

            like = context.like.Where(s => s.liked_by == userId && s.post_liked == id).FirstOrDefault();
            Post p = context.post.Find(id);
            User u = context.user.Find(p.postedBy);

            if (like == null)
            {
                p.like_count          += 1;
                context.Entry(p).State = EntityState.Modified;
                u.like_recieved       += 1;
                context.Entry(u).State = EntityState.Modified;
                //context.SaveChanges();
                Like like1 = new Like();
                like1.post_liked = id;
                like1.liked_by   = Convert.ToInt32(userId);
                context.like.Add(like1);
                context.SaveChanges();
            }
            else if (like != null)
            {
                //Post p = context.post.Find(id);
                p.like_count          -= 1;
                u.like_recieved       -= 1;
                context.Entry(u).State = EntityState.Modified;
                context.Entry(p).State = EntityState.Modified;
                //context.SaveChanges();
                context.like.Attach(like);
                context.like.Remove(like);
                context.SaveChanges();
            }
            return(RedirectToAction("Details", "Thread", new { id = p.ThreadID }));
        }