Esempio n. 1
0
        public ActionResult AddPost(Post newPost)
        {
            db.Posts.Add(newPost);
            int res = db.SaveChanges();

            return(Json(new { status = res, Post = newPost }));
        }
Esempio n. 2
0
        public ActionResult Create([Bind(Include = "Id,Name,ShortDescription,Description,Date,CategoryId,PictureNmae,Image")] Article article, int selectedCategory, HttpPostedFileBase uploadImage)
        {
            article.Categories = new List <Category>();
            if (selectedCategory != null)
            {
                foreach (var c in db.Categories.Where(co => selectedCategory == co.CategoryId))
                {
                    article.Categories.Add(c);
                }
            }
            article.Date = DateTime.Now;
            if (uploadImage != null)
            {
                byte[] imageData = null;
                using (var binaryReader = new BinaryReader(uploadImage.InputStream))
                {
                    imageData = binaryReader.ReadBytes(uploadImage.ContentLength);
                }
                article.Image = imageData;
            }
            if (ModelState.IsValid)
            {
                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name" /*, article.CategoryId*/);
            return(View(article));
        }
Esempio n. 3
0
        public IActionResult Register([FromBody] RegisterUserDTO registerUserDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User newUser = new User()
            {
                Email       = registerUserDTO.Email,
                Country     = registerUserDTO.Country,
                DateOfBirth = registerUserDTO.DateOfBirth.HasValue ? registerUserDTO.DateOfBirth : DateTime.Now,
                isActive    = "active",
                RoleId      = registerUserDTO.RoleId
            };

            var passwordHash = _passwordHasher.HashPassword(newUser, registerUserDTO.PasswordHash);

            newUser.PasswordHash = passwordHash;

            _articleContext.Users.Add(newUser);
            _articleContext.SaveChanges();

            _logger.LogWarning($"Dodano nowego uzytkownika - {newUser.Email}, RoleID - {newUser.RoleId}");

            return(Ok());
        }
Esempio n. 4
0
        public ActionResult Index(Poll poll)
        {
            if (ip != HttpContext.Request.UserHostAddress)
            {
                Session["isfirstsubmit"] = "true";
                ip = HttpContext.Request.UserHostAddress;
                foreach (Variant var in this.poll.Variants)
                {
                    if (var.Text == poll.SelectedVariant)
                    {
                        var.Vote++;
                    }

                    this.poll.Sum += var.Vote;
                }
                db.Polls.Find(0).Sum      = poll.Sum;
                db.Polls.Find(0).Variants = poll.Variants;
                db.SaveChanges();
            }
            else
            {
                Session["isfirstsubmit"] = "false";
            }
            IEnumerable <Article> articles = db.Articles.ToList();

            return(View(articles));
        }
 public ActionResult Comment([Bind(Include = "ArticleId, Comment")] ArticleComments artComment)
 {
     if (artComment.ArticleId <= 0)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You have passed an invalid article."));
     }
     if (db.Articles.Any((art => art.Id == artComment.ArticleId)))
     {
         if (string.IsNullOrWhiteSpace(artComment.Comment))
         {
             TempData["EmptyComment"] = true;
         }
         else
         {
             artComment.Date   = DateTime.Now;
             artComment.UserId = User.Identity.Name;
             db.Comments.Add(artComment);
             db.SaveChanges();
         }
     }
     else
     {
         return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Article does not exist."));
     }
     return(RedirectToAction("Details", new { id = artComment.ArticleId }));
 }
Esempio n. 6
0
        public void Add(T entity)
        {
            EntityEntry dbEntityEntry = context.Entry <T>(entity);

            context.Set <T>().Add(entity);

            context.SaveChanges();
        }
Esempio n. 7
0
        public ActionResult Create([Bind(Include = "ID,Title,Date,Author,Content")] Article article)
        {
            if (ModelState.IsValid)
            {
                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(article));
        }
Esempio n. 8
0
        public ActionResult Create([Bind(Include = "CategoryName")] Category category)
        {
            if (ModelState.IsValid)
            {
                db.Categories.Add(category);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(category));
        }
Esempio n. 9
0
        public ActionResult Create([Bind(Include = "Id,Name,Price")] Article article)
        {
            if (ModelState.IsValid)
            {
                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(article));
        }
Esempio n. 10
0
 public bool Delete(T entity)
 {
     _dbContext.Set <T>().Remove(entity);
     try
     {
         return(_dbContext.SaveChanges() > 0);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 11
0
        public ActionResult Delete(int id)
        {
            Article dbEntry = db.Articles.Find(id);

            if (dbEntry != null)
            {
                db.Articles.Remove(dbEntry);
                db.SaveChanges();
                TempData["message"] = string.Format("Статья \"{0}\" была удалена", dbEntry.Name);
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 12
0
        public ActionResult Create(Article article)
        {
            HttpCookie cookie = Request.Cookies["UserInfo"];

            if (cookie != null)
            {
                article.Author = cookie["Username"];
            }
            db.Articles.Add(article);
            db.SaveChanges();
            return(Redirect("/Home/Index"));
        }
Esempio n. 13
0
        public ActionResult Create([Bind(Include = "Header,Description,Content,CategoryId")] Article article)
        {
            if (ModelState.IsValid)
            {
                article.DateOfAdding = DateTime.Now;

                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", article.CategoryId);
            return(View(article));
        }
Esempio n. 14
0
        public int Save(IPlan entity, bool now = true)
        {
            try
            {
                if (entity == null)
                {
                    return(-1);
                }
                using (Container = new ArticleContext())
                {
                    var current = entity as CurrentPlan;
                    var planDb  = Mapper.Map <CurrentPlan, Plan>(current);
                    if (Container.Plans.FirstOrDefault(c => c.Name == entity.Name) != null)
                    {
                        throw new Exception("Найден план с таким же названием");
                    }


                    Container.Plans.Add(planDb);
                    if (now)
                    {
                        Container.SaveChanges();
                    }
                    entity.Id = planDb.Id;

                    TransactionHelper.AddTransaction(Container, ActionType.Adding, planDb, _currentUser);
                    if (now)
                    {
                        Container.SaveChanges();
                    }
                    return(planDb.Id);
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw;
            }
            catch (Exception e)
            {
                throw;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="article"></param>
        public string AddArticle(Article article)
        {
            var check = _classificationContext.Classification.Where(c => c.Id == article.ClassificationId && article.UserId == c.UserId).FirstOrDefault();

            if (check == null)
            {
                return("添加文章的分类不存在");
            }
            _articleContext.Add(article);
            if (_articleContext.SaveChanges() == 1)
            {
                return("文章添加成功");
            }
            return("文章添加失败");
        }
Esempio n. 16
0
        public async Task <IActionResult> DeleteArticle(int id)
        {
            Article art = await _context.Article
                          .Where(x => x.ArticleId == id)
                          .FirstOrDefaultAsync();

            var result = _context.Article.Remove(art);

            _context.SaveChanges();

            return(new JsonResult("")
            {
                StatusCode = 202
            });
        }
Esempio n. 17
0
 public IPlan Read(int id)
 {
     try
     {
         if (id <= 0)
         {
             return(null);
         }
         using (Container = new ArticleContext())
         {
             var artDb = Container.Plans.FirstOrNothing(c => c.Id == id);
             if (artDb.HasValue)
             {
                 TransactionHelper.AddTransaction(Container, ActionType.Read, artDb.Value, _currentUser);
                 Container.SaveChanges();
             }
             return(artDb.Bind(Mapper.Map <Entities.Plan, CurrentPlan>).GetOrDefault(null));
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw;
     }
     catch (Exception e)
     {
         throw;
     }
 }
        public ActionResult AddComment(Comment comment)
        {
            Post post = db.Posts.SingleOrDefault(b => b.PostID == comment.PostID);

            post.Comments.Add(comment);
            return(Json(new { status = db.SaveChanges() }));
        }
Esempio n. 19
0
 public IEnumerable <Comment> SaveMany(IEnumerable <Comment> entities)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             var list       = new List <Entities.Comment>();
             var enumerable = entities as Comment[] ?? entities.ToArray();
             foreach (var comment in enumerable)
             {
                 var commentDb = Mapper.Map <Comment, Entities.Comment>(comment);
                 var user      = Container.Users.First(c => c.UserId == commentDb.UserId);
                 TransactionHelper.AddTransaction(Container, ActionType.Adding, commentDb, user);
                 Container.Comments.Add(commentDb);
             }
             Container.SaveChanges();
             return(enumerable);
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw;
     }
     catch (Exception e)
     {
         throw;
     }
 }
Esempio n. 20
0
 public void AddArticle(Article article)
 {
     article.Date = DateTime.UtcNow;
     article.Date = article.Date.Add(new TimeSpan(3, 0, 0));
     db.Articles.Add(article);
     db.SaveChanges();
 }
Esempio n. 21
0
 private void AddTestArticleToDb()
 {
     using (ArticleContext context = CreateDbContext())
     {
         ArticleModel am = new ArticleModel()
         {
             Id          = 1,
             Title       = _testArticleTitle,
             Content     = _testContent,
             PublishTime = _testPublishTime,
             Thumbnail   = new ImageReferenceModel()
             {
                 AltText  = _testImageAltText,
                 Location = _testImageLocation
             }
         };
         Tag testTag2 = new Tag(2, "Test Tag 2");
         Tag testTag3 = new Tag(3, "Test Tag 3");
         context.Tags.Add(testTag2);
         context.Tags.Add(testTag3);
         am.ArticleTags.Add(new ArticleTagModel()
         {
             Article = am,
             Tag     = testTag2
         });
         am.ArticleTags.Add(new ArticleTagModel()
         {
             Article = am,
             Tag     = testTag3
         });
         context.ArticleModels.Add(am);
         context.SaveChanges();
     }
 }
Esempio n. 22
0
        public string Export(int articleId)
        {
            Article article = null;

            using (Container = new ArticleContext())
            {
                article = Container.Articles.FirstOrNothing(c => c.ArticleId == articleId).Bind(Mapper.Map <Entities.Article, Article>).GetOrDefault(null);
                TransactionHelper.AddTransaction(Container, ActionType.Export, null, _currentUser);
                Container.SaveChanges();
            }

            var xmlAricle = new XmlArticle
            {
                Article = article
            };

            using (var stream = XmlArticle.Serialize(xmlAricle.GetType(), xmlAricle))
            {
                stream.Position = 0;
                var document        = new XDocument(new XElement("Articles"));
                var anotherDocument = XDocument.Load(stream);
                document.Root.Add(anotherDocument.Root.Elements().First());
                return(document.ToString());
            }
        }
Esempio n. 23
0
        public override string Export()
        {
            using (Container = new ArticleContext())
            {
                TransactionHelper.AddTransaction(Container, ActionType.Export, null, _currentUser);
                Container.SaveChanges();
            }

            var all    = GetAll(new QueryParams <Article>(0, 999, c => c.ArticleId));
            var allXml = all.Select(c => new XmlArticle {
                Article = c
            }).OrderBy(c => c.Article.ArticleId).ToList();

            using (var stream = XmlArticle.Serialize(allXml.GetType(), allXml))
            {
                stream.Position = 0;
                var document        = new XDocument(new XElement("Articles"));
                var anotherDocument = XDocument.Load(stream);
                foreach (var xNode in anotherDocument.Root.Elements().Select(c => c.Elements().First()))
                {
                    document.Root.Add(xNode);
                }
                return(document.ToString());
            }
        }
Esempio n. 24
0
        private void InsertSampleData()
        {
            List <Article> articles = DefaultArticles();

            _articleContext.AddRange(articles);
            _articleContext.SaveChanges();
        }
Esempio n. 25
0
 public string Guestbook(Review review)
 {
     review.Rdate = DateTime.Now;
     db.Reviews.Add(review);
     db.SaveChanges();
     return("Спасибо," + review.Rname + ", за отзыв!");
 }
Esempio n. 26
0
 public void Delete(ArticleGroup entity, bool now = true)
 {
     if (entity.GroupId == 1)
     {
         throw new Exception("Не возможно удалить группу по умолчанию");
     }
     ExecuteWithTry(() =>
     {
         using (Container = new ArticleContext())
         {
             var existingArticles = Container.Articles.Where(c => c.Group.GroupId == entity.GroupId);
             var defaultGroup     = Container.Groups.FirstOrDefault(c => c.GroupId == 1);
             foreach (var existingArticle in existingArticles)
             {
                 existingArticle.Group = defaultGroup;
             }
             var fromDb = Container.Groups.First(c => c.GroupId == entity.GroupId);
             TransactionHelper.AddTransaction(Container, ActionType.Deleting, fromDb, _currentUser);
             Container.Groups.Remove(fromDb);
             if (now)
             {
                 Container.SaveChanges();
             }
             return(0);
         }
     });
 }
Esempio n. 27
0
        public int Save(ITag entity, bool now = true)
        {
            try
            {
                if (entity == null)
                {
                    return(-1);
                }
                using (Container = new ArticleContext())
                {
                    var tagDb = Mapper.Map <Tag, Entities.Tag>(entity as Tag);
                    if (Container.Tags.FirstOrDefault(c => c.Name == tagDb.Name) != null)
                    {
                        throw new Exception("Найден тэг с таким же именем.Тэг не будет сохранен.");
                    }


                    Container.Tags.Add(tagDb);
                    if (now)
                    {
                        Container.SaveChanges();
                    }
                    entity.Id = tagDb.Id;
                    TransactionHelper.AddTransaction(Container, ActionType.Adding, tagDb, _currentUser);
                    if (now)
                    {
                        Container.SaveChanges();
                    }
                    return(tagDb.Id);
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw;
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public ActionResult Create([Bind(Include = "ArticleID,Title,Content,Category,ArticleStatus,ArticleCover")] Article article)
        {
            if (ModelState.IsValid)
            {
                article.PublishDate   = DateTime.Now;
                article.ArticleID     = Guid.NewGuid();
                article.AuthorID      = User.Identity.GetUserId();
                article.ArticleStatus = "I";
                article.ModifiedOn    = DateTime.Now;

                db.Articles.Add(article);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(article));
        }
Esempio n. 29
0
        void IVote.Vote(int id)
        {
            var article = db.Articles.Find(id);

            article.Rating += 1;

            db.SaveChanges();
        }
        public ActionResult Create([Bind(Include = "Id,Name,Article")] Location location)
        {
            if (ModelState.IsValid)
            {
                var article = db.Articles.Where(a => a.Name.Equals(location.Article)).FirstOrDefault();
                if (article != null)
                {
                    int id = article.Id;
                    location.Article_Id = id;
                    db.Locations.Add(location);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(location));
        }