Ejemplo n.º 1
0
        public IHttpActionResult Post(ArticleBindingModel articleBindingModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Article article = Mapper.Map <ArticleBindingModel, Article>(articleBindingModel);

            var userId = User.Identity.GetUserId();

            if (userId == null)
            {
                return(BadRequest());
            }

            var user = _userService.GetById(userId);

            article.User = user;

            _articleService.Add(article);
            var articleViewModel = Mapper.Map <Article, ArticleViewModel>(article);

            return(Ok(articleViewModel));
        }
Ejemplo n.º 2
0
 public void CreateOrUpdate(ArticleBindingModel model)
 {
     using (var context = new Database())
     {
         Article element = context.Articles.FirstOrDefault(rec => rec.Name == model.Name && rec.Id != model.Id);
         if (element != null)
         {
             throw new Exception("Уже есть статья с таким названием");
         }
         if (model.Id.HasValue)
         {
             element = context.Articles.FirstOrDefault(rec => rec.Id ==
                                                       model.Id);
             if (element == null)
             {
                 throw new Exception("Элемент не найден");
             }
         }
         else
         {
             element = new Article();
             context.Articles.Add(element);
         }
         element.Name       = model.Name;
         element.Theme      = model.Theme;
         element.DateCreate = model.DateCreate;
         context.SaveChanges();
     }
 }
Ejemplo n.º 3
0
        public async Task <IActionResult> Put(int id, [FromBody] ArticleBindingModel articleModel)
        {
            _logger.LogInformation($"Modification of the article {id} started.");

            var userId  = User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var isOwner = await _articleService.IsOwnerAsync(id, userId);

            if (!isOwner)
            {
                _logger.LogWarning($"User {userId} is not allowed to modify article {id}.");
                return(Forbid());
            }

            var articleDto = new ArticleDto
            {
                Content     = articleModel.Content,
                Description = articleModel.Description,
                Title       = articleModel.Title
            };

            articleDto = await _articleService.UpdateAsync(id, articleDto);

            _logger.LogInformation($"Modification of the article {id} finished.");

            return(Ok(articleDto));
        }
Ejemplo n.º 4
0
 public void Insert(ArticleBindingModel model)
 {
     using (var context = new NewsBlogDatabase())
     {
         context.Articles.Add(CreateModel(model, new Articles()));
         context.SaveChanges();
     }
 }
Ejemplo n.º 5
0
 private Articles CreateModel(ArticleBindingModel model, Articles article)
 {
     article.Title   = model.Title;
     article.Text    = model.Text;
     article.Date    = model.DateCreate;
     article.Iduser  = model.UserId;
     article.Idtheme = model.CategoryId;
     return(article);
 }
        public void AddElement(ArticleBindingModel model)
        {
            int maxId = 0;

            for (int i = 0; i < source.Articles.Count; ++i)
            {
                if (source.Articles[i].Id > maxId)
                {
                    maxId = source.Articles[i].Id;
                }
                if (source.Articles[i].ArticleName == model.ArticleName)
                {
                    throw new Exception("Уже есть изделие с таким названием");
                }
            }
            source.Articles.Add(new Article
            {
                Id          = maxId + 1,
                ArticleName = model.ArticleName,
                Price       = model.Price
            });
            // компоненты для изделия
            int maxPCId = 0;

            for (int i = 0; i < source.ArticleIngridients.Count; ++i)
            {
                if (source.ArticleIngridients[i].Id > maxPCId)
                {
                    maxPCId = source.ArticleIngridients[i].Id;
                }
            }
            // убираем дубли по компонентам
            for (int i = 0; i < model.ArticleIngridients.Count; ++i)
            {
                for (int j = 1; j < model.ArticleIngridients.Count; ++j)
                {
                    if (model.ArticleIngridients[i].IngridientId ==
                        model.ArticleIngridients[j].IngridientId)
                    {
                        model.ArticleIngridients[i].Count +=
                            model.ArticleIngridients[j].Count;
                        model.ArticleIngridients.RemoveAt(j--);
                    }
                }
            }
            // добавляем компоненты
            for (int i = 0; i < model.ArticleIngridients.Count; ++i)
            {
                source.ArticleIngridients.Add(new ArticleIngridient
                {
                    Id           = ++maxPCId,
                    ArticleId    = maxId + 1,
                    IngridientId = model.ArticleIngridients[i].IngridientId,
                    Count        = model.ArticleIngridients[i].Count
                });
            }
        }
Ejemplo n.º 7
0
        public ArticleBindingModel AddArticle(ArticleBindingModel model)
        {
            var article = Mapper.Map <Article>(model);

            DbContext.Articles.Add(article);
            DbContext.SaveChanges();

            Mapper.Map(article, model);
            return(model);
        }
Ejemplo n.º 8
0
 public void Update(ArticleBindingModel model)
 {
     using (var context = new NewsBlogDatabase())
     {
         var article = context.Articles.FirstOrDefault(rec => rec.Idarticle == model.Id);
         if (article == null)
         {
             throw new Exception("Статья не найдена");
         }
         CreateModel(model, article);
         context.SaveChanges();
     }
 }
Ejemplo n.º 9
0
        public void Delete(ArticleBindingModel model)
        {
            var article = _articleStorage.GetElement(new ArticleBindingModel
            {
                Id = model.Id
            });

            if (article == null)
            {
                throw new Exception("Статья не найдена");
            }
            _articleStorage.Delete(model);
        }
Ejemplo n.º 10
0
        public ArticleBindingModel GetArticleById(int id)
        {
            var model     = new ArticleBindingModel();
            var articleDb = DbContext.Articles.Find(id);

            if (articleDb == null)
            {
                model.SetError("No such article in database");
                return(model);
            }

            model = Mapper.Map <ArticleBindingModel>(articleDb);
            return(model);
        }
Ejemplo n.º 11
0
 public List <ArticleViewModel> Read(ArticleBindingModel model)
 {
     if (model == null)
     {
         return(_articleStorage.GetFullList());
     }
     if (model.Id.HasValue)
     {
         return(new List <ArticleViewModel> {
             _articleStorage.GetElement(model)
         });
     }
     return(_articleStorage.GetFilteredList(model));
 }
Ejemplo n.º 12
0
        public async Task <IActionResult> Add(ArticleBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            var article = this.mapper.Map <ArticleBindingModel, Article>(model);

            await this._as.Create(article);

            this.TempData["SuccessMsg"] = "Article has been created successfully.";

            return(this.RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 13
0
 public List <ArticleViewModel> Read(ArticleBindingModel model)
 {
     using (var context = new Database())
     {
         return(context.Articles
                .Where(rec => model == null || rec.Id == model.Id)
                .Select(rec => new ArticleViewModel
         {
             Id = rec.Id,
             Name = rec.Name,
             Theme = rec.Theme,
             DateCreate = rec.DateCreate
         })
                .ToList());
     }
 }
Ejemplo n.º 14
0
 public void Delete(ArticleBindingModel model)
 {
     using (var context = new NewsBlogDatabase())
     {
         Articles article = context.Articles.FirstOrDefault(rec => rec.Idarticle == model.Id);
         if (article != null)
         {
             context.Articles.Remove(article);
             context.SaveChanges();
         }
         else
         {
             throw new Exception("Статья не найдена");
         }
     }
 }
Ejemplo n.º 15
0
        public async Task <IActionResult> Edit(ArticleBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);
                return(this.View(model));
            }

            var article = this.mapper.Map <ArticleBindingModel, Article>(model);

            await this._as.Update(article);

            this.TempData["SuccessMsg"] = "Article has been created successfully.";

            return(this.RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 16
0
        public ArticleBindingModel DeleteArticle(int id)
        {
            var model     = new ArticleBindingModel();
            var articleDb = DbContext.Articles.Find(id);

            if (articleDb == null)
            {
                model.SetError("No such article in database");
                return(model);
            }

            DbContext.Articles.Remove(articleDb);
            DbContext.SaveChanges();

            Mapper.Map(articleDb, model);
            return(model);
        }
Ejemplo n.º 17
0
        public void AddElement(ArticleBindingModel article)
        {
            int maxId = 0;

            for (int i = 0; i < source.Articles.Count; i++)
            {
                if (source.Articles[i].Id > maxId)
                {
                    maxId = source.Articles[i].Id;
                }
                if (source.Articles[i].Title == article.Title)
                {
                    throw new Exception("Уже есть такая статья");
                }
            }
            source.Articles.Add(new Article
            {
                Id         = maxId + 1,
                Title      = article.Title,
                Subject    = article.Subject,
                DateCreate = article.DateCreate
            });

            int maxAId = 0;

            for (int i = 0; i < source.Authors.Count; i++)
            {
                if (source.Authors[i].Id == maxAId)
                {
                    maxAId = source.Authors[i].Id;
                }
            }
            for (int i = 0; i < source.Authors.Count; i++)
            {
                source.Authors.Add(new Author
                {
                    Id        = maxAId + 1,
                    AuthorFIO = source.Authors[i].AuthorFIO,
                    DateBirth = source.Authors[i].DateBirth,
                    Job       = source.Authors[i].Job,
                    Email     = source.Authors[i].Job,
                    ArticleId = maxId + 1,
                    Article   = source.Authors[i].Article
                });
            }
        }
Ejemplo n.º 18
0
 public void Delete(ArticleBindingModel model)
 {
     using (var context = new Database())
     {
         Article element = context.Articles.FirstOrDefault(rec => rec.Id ==
                                                           model.Id);
         if (element != null)
         {
             context.Articles.Remove(element);
             context.SaveChanges();
         }
         else
         {
             throw new Exception("Элемент не найден");
         }
     }
 }
Ejemplo n.º 19
0
        public ArticleBindingModel EditArticle(ArticleBindingModel model)
        {
            var articleDb = DbContext.Articles.Find(model.Id);

            if (articleDb == null)
            {
                model.SetError("No such article in database");
                return(model);
            }

            Mapper.Map(model, articleDb);

            DbContext.Articles.Update(articleDb);
            DbContext.SaveChanges();

            Mapper.Map(articleDb, model);
            return(model);
        }
Ejemplo n.º 20
0
        public IHttpActionResult Put([FromBody] ArticleBindingModel articleBindingModel)
        {
            var arcticle = _articleService.GetById(articleBindingModel.Id);
            var userId   = User.Identity.GetUserId();

            if (ModelState.IsValid && articleBindingModel.Id == arcticle.Id && userId == arcticle.User.Id || User.IsInRole(UserRoles.Administrator))
            {
                Mapper.Map(articleBindingModel, arcticle);

                _articleService.UpdateArticle(arcticle);

                var articleModified = Mapper.Map <Article, ArticleViewModel>(arcticle);

                return(Ok(articleModified));
            }

            return(StatusCode(HttpStatusCode.NotModified));
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> Post([FromBody] ArticleBindingModel articleModel)
        {
            _logger.LogInformation($"Posting a new article");

            var userId = User.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;

            var articleDto = new ArticleDto
            {
                Content     = articleModel.Content,
                Description = articleModel.Description,
                Title       = articleModel.Title
            };
            var article = await _articleService.InsertAsync(articleDto, userId);

            _logger.LogInformation($"Posting a new article finished!");

            return(Ok(article));
        }
Ejemplo n.º 22
0
        public IActionResult Edit(ArticleBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(this.View(model));
            }

            var result = this.articleService.EditArticle(model);

            LogResult(result);

            if (result.HasError)
            {
                SetMessage(MessageType.Danger, result.Message);
                return(this.View(result));
            }

            SetMessage(MessageType.Success, $"Article edited successfully");
            return(this.RedirectToAction("All"));
        }
Ejemplo n.º 23
0
        public void CreateOrUpdate(ArticleBindingModel model)
        {
            var article = _articleStorage.GetElement(new ArticleBindingModel
            {
                Title = model.Title
            });

            if (article != null && article.Id != model.Id)
            {
                throw new Exception("Уже есть статья с таким названием");
            }
            if (model.Id.HasValue)
            {
                _articleStorage.Update(model);
            }
            else
            {
                _articleStorage.Insert(model);
            }
        }
Ejemplo n.º 24
0
        // get by id
        public async Task<ArticleBindingModel> GetById(int id)
        {
            var article =  await _repositoryManager.ArticleRepository.GetAsync(id);

            // load article tags
            var tags = await _repositoryManager.ArticleTagRepository
                                               .Table
                                               .Where(m => m.ArticleId == id)
                                               .ToListAsync();

            // return bindig model model
            var binding = new ArticleBindingModel
            {
                ArticleId = article.ArticleId,
                Title = article.Title,
                Content = article.Body,
                TagIds = tags.Select(m => m.TagId)
            };

            return binding;
        }
Ejemplo n.º 25
0
        public IActionResult Add(ArticleBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(this.View(model));
            }

            model.AuthorId    = this.userManager.GetUserId(this.User);
            model.CreatedDate = DateTime.Now;

            var result = this.articleService.AddArticle(model);

            LogResult(result);

            if (result.HasError)
            {
                SetMessage(MessageType.Danger, result.Message);
                return(this.View(model));
            }

            SetMessage(MessageType.Success, $"Article added successfully");
            return(this.RedirectToAction("All"));
        }
Ejemplo n.º 26
0
 public List <ArticleViewModel> GetFilteredList(ArticleBindingModel model)
 {
     if (model == null)
     {
         return(null);
     }
     using (var context = new NewsBlogDatabase())
     {
         return(context.Articles
                .Include(rec => rec.IdthemeNavigation)
                .Include(rec => rec.IduserNavigation)
                .Where(rec => rec.Title.Contains(model.Title) || (!model.DateFrom.HasValue && !model.DateTo.HasValue && rec.Date.Date == model.DateCreate.Date) ||
                       (model.DateFrom.HasValue && model.DateTo.HasValue && rec.Date.Date >= model.DateFrom.Value.Date && rec.Date.Date <= model.DateTo.Value.Date))
                .Select(rec => new ArticleViewModel
         {
             Id = rec.Idarticle,
             Title = rec.Title,
             Text = rec.Text,
             DateCreate = rec.Date,
             CategoryId = rec.Idtheme,
             UserId = rec.Iduser
         }).ToList());
     }
 }
Ejemplo n.º 27
0
 public ArticleViewModel GetElement(ArticleBindingModel model)
 {
     if (model == null)
     {
         return(null);
     }
     using (var context = new NewsBlogDatabase())
     {
         var article = context.Articles
                       .Include(rec => rec.IdthemeNavigation)
                       .Include(rec => rec.IduserNavigation)
                       .FirstOrDefault(rec => rec.Title.Equals(model.Title) || rec.Idarticle == model.Id);
         return(article != null ?
                new ArticleViewModel
         {
             Id = article.Idarticle,
             Title = article.Title,
             Text = article.Text,
             DateCreate = article.Date,
             CategoryId = article.Idtheme,
             UserId = article.Iduser
         } : null);
     }
 }
 public void NotifyClients(ArticleBindingModel articleAdded)
 {
     Clients.All.broadcastMessage(articleAdded);
 }
Ejemplo n.º 29
0
        public void UpdElement(ArticleBindingModel article)
        {
            int index = -1;

            for (int i = 0; i < source.Articles.Count; i++)
            {
                if (source.Articles[i].Id == article.Id)
                {
                    index = i;
                }
                if (source.Articles[i].Title == article.Title &&
                    source.Articles[i].Subject == article.Subject &&
                    source.Articles[i].DateCreate == article.DateCreate &&
                    source.Articles[i].Id != article.Id)
                {
                    throw new Exception("Уже есть такая статья");
                }
            }

            if (index == -1)
            {
                throw new Exception("Элемент не найден");
            }

            source.Articles[index].Title      = article.Title;
            source.Articles[index].Subject    = article.Subject;
            source.Articles[index].DateCreate = article.DateCreate;

            int maxAId = 0;

            for (int i = 0; i < source.Authors.Count; i++)
            {
                if (source.Authors[i].Id == maxAId)
                {
                    maxAId = source.Authors[i].Id;
                }
            }
            for (int i = 0; i < source.Authors.Count; i++)
            {
                if (article.Authors[i].ArticleId == article.Id)
                {
                    for (int j = 0; j < source.Authors.Count; j++)
                    {
                        if (source.Authors[i].Id != article.Authors[j].Id)
                        {
                            source.Authors.RemoveAt(i--);
                        }
                    }
                }
            }

            for (int i = 0; i < source.Authors.Count; i++)
            {
                if (article.Authors[i].Id == 0)
                {
                    source.Authors.Add(new Author
                    {
                        Id        = maxAId + 1,
                        AuthorFIO = article.Authors[i].AuthorFIO,
                        DateBirth = article.Authors[i].DateBirth,
                        Email     = article.Authors[i].Email,
                        Job       = article.Authors[i].Job,
                        ArticleId = article.Id
                    });
                }
            }
        }
Ejemplo n.º 30
0
        public IActionResult Add()
        {
            var model = new ArticleBindingModel();

            return(this.View(model));
        }
        public void UpdElement(ArticleBindingModel model)
        {
            int index = -1;

            for (int i = 0; i < source.Articles.Count; ++i)
            {
                if (source.Articles[i].Id == model.Id)
                {
                    index = i;
                }
                if (source.Articles[i].ArticleName == model.ArticleName &&
                    source.Articles[i].Id != model.Id)
                {
                    throw new Exception("Уже есть изделие с таким названием");
                }
            }
            if (index == -1)
            {
                throw new Exception("Элемент не найден");
            }
            source.Articles[index].ArticleName = model.ArticleName;
            source.Articles[index].Price       = model.Price;
            int maxPCId = 0;

            for (int i = 0; i < source.ArticleIngridients.Count; ++i)
            {
                if (source.ArticleIngridients[i].Id > maxPCId)
                {
                    maxPCId = source.ArticleIngridients[i].Id;
                }
            }
            // обновляем существуюущие компоненты
            for (int i = 0; i < source.ArticleIngridients.Count; ++i)
            {
                if (source.ArticleIngridients[i].ArticleId == model.Id)
                {
                    bool flag = true;
                    for (int j = 0; j < model.ArticleIngridients.Count; ++j)
                    {
                        // если встретили, то изменяем количество
                        if (source.ArticleIngridients[i].Id == model.ArticleIngridients[j].Id)
                        {
                            source.ArticleIngridients[i].Count = model.ArticleIngridients[j].Count;
                            flag = false;
                            break;
                        }
                    }
                    // если не встретили, то удаляем
                    if (flag)
                    {
                        source.ArticleIngridients.RemoveAt(i--);
                    }
                }
            }
            // новые записи
            for (int i = 0; i < model.ArticleIngridients.Count; ++i)
            {
                if (model.ArticleIngridients[i].Id == 0)
                {
                    // ищем дубли
                    for (int j = 0; j < source.ArticleIngridients.Count; ++j)
                    {
                        if (source.ArticleIngridients[j].ArticleId == model.Id &&
                            source.ArticleIngridients[j].IngridientId == model.ArticleIngridients[i].IngridientId)
                        {
                            source.ArticleIngridients[j].Count += model.ArticleIngridients[i].Count;
                            model.ArticleIngridients[i].Id      = source.ArticleIngridients[j].Id;
                            break;
                        }
                    }
                    // если не нашли дубли, то новая запись
                    if (model.ArticleIngridients[i].Id == 0)
                    {
                        source.ArticleIngridients.Add(new ArticleIngridient
                        {
                            Id           = ++maxPCId,
                            ArticleId    = model.Id,
                            IngridientId = model.ArticleIngridients[i].IngridientId,
                            Count        = model.ArticleIngridients[i].Count
                        });
                    }
                }
            }
        }