Exemple #1
0
 public IEnumerable <Comment> GetBySqlPredicate(string sql, params object[] args)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             var res = Container.Database.SqlQuery <Entities.Comment>(sql, args).ToList();
             return(Mapper.Map <List <Entities.Comment>, List <Comment> >(res));
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw;
     }
     catch (Exception e)
     {
         throw;
     }
 }
Exemple #2
0
 public IEnumerable <T1> GetBySqlPredicate <T1>(string sql, params object[] args)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             return(Container.Database.SqlQuery <T1>(sql, args).ToList());
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw;
     }
     catch (Exception e)
     {
         throw;
     }
 }
Exemple #3
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;
     }
 }
Exemple #4
0
 public IEnumerable <Article> GetBySqlPredicate(string sql, params object[] args)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             return(Container.Database.SqlQuery <Entities.Article>(sql, args)
                    .ToList()
                    .MaybeAs <List <Entities.Article> >()
                    .Bind(Mapper.Map <List <Entities.Article>, List <Article> >)
                    .GetOrDefault(new List <Article>()));
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw;
     }
     catch (Exception e)
     {
         throw;
     }
 }
Exemple #5
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());
            }
        }
Exemple #6
0
 public User Read(int id)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             var user = Container.Users.FirstOrDefault(c => c.UserId == id);
             if (user != null)
             {
                 return(Mapper.Map <Entities.User, User>(user));
             }
             return(null);
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw ex;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #7
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);
         }
     });
 }
Exemple #8
0
        public async Task Update_TestArticle_UpdatesThumbnail()
        {
            AddTestArticleToDb();

            using (ArticleContext actContext = CreateDbContext())
            {
                ArticleRepository repo = new ArticleRepository(actContext);

                var testArticle = await repo.GetByIdAsync(1);

                testArticle.Thumbnail = new ImageReference(_testImageLocation, "NewAltText");
                await repo.UpdateAsync(testArticle);

                await actContext.SaveEntitiesAsync();
            }

            using (ArticleContext assertContext = CreateDbContext())
            {
                ArticleModel testModel = await assertContext.ArticleModels.FirstOrDefaultAsync();

                Assert.NotNull(testModel);

                Assert.Equal("NewAltText", testModel.Thumbnail.AltText);
            }
        }
Exemple #9
0
        public async Task Update_TestArticle_UpdatesTags()
        {
            AddTestArticleToDb();

            using (ArticleContext actContext = CreateDbContext())
            {
                ArticleRepository repo = new ArticleRepository(actContext);

                var testArticle = await repo.GetByIdAsync(1);

                testArticle.ReplaceTagIds(new [] { 3, 4 });
                await repo.UpdateAsync(testArticle);

                await actContext.SaveEntitiesAsync();
            }

            using (ArticleContext assertContext = CreateDbContext())
            {
                ArticleModel testModel = await assertContext.ArticleModels.FirstOrDefaultAsync();

                assertContext.Entry(testModel).Navigation("ArticleTags").Load();

                Assert.NotNull(testModel);

                Assert.Equal(new[] { 3, 4 }, testModel.ArticleTags.Select(at => at.TagId).OrderBy(i => i));
            }
        }
        public void InsertNewArticleTest()
        {
            ArticleContext articles = new ArticleContext();
            Article        test     = new Article
            {
                Caption    = "TestCaption2",
                Text       = "Test text",
                Date       = DateTime.Now,
                Language   = "Eng",
                Video      = "testlinkVideo",
                Image      = "testlinkImage",
                CategoryId = 1,
                User       = new User
                {
                    Name = "Boris"
                }
            };
            int countArticles = articles.GetCountArticles(null);

            articles.InsertNewArticle(test);
            int afterInsert = articles.GetCountArticles(null);

            Assert.AreNotEqual(countArticles, afterInsert);
            Assert.IsTrue((countArticles + 1) == afterInsert);
        }
        public void UpdateArticleTest()
        {
            ArticleContext articles = new ArticleContext();
            Article        test     = new Article
            {
                ArticleId  = 33,
                Caption    = "TestCaption2Update",
                Text       = "Test text text test test",
                Date       = DateTime.Now,
                Language   = "Eng",
                Video      = "testlinkVideo",
                Image      = "testlinkImage",
                CategoryId = 1,
                User       = new User
                {
                    Name = "Boris"
                }
            };
            string oldName = articles.GetArticle(33).Caption;

            articles.UpdateArticle(test);
            string newName = articles.GetArticle(33).Caption;

            Assert.AreNotEqual(oldName, newName);
        }
 public FavoriteController(ApplicationContext contextApp, ArticleContext contextArt, IGetFavorite getFavorite, IGetArticle getArticle)
 {
     db           = contextArt;
     dbUsers      = contextApp;
     _getFavorite = getFavorite;
     _getArticle  = getArticle;
 }
 public BlogCommentService(IGenericRepository <BlogComment> blogRepo, UnitOfWork unitOfWork, ArticleContext context, BlogCommentManager blogCommentManager)
 {
     this.blogRepo           = blogRepo;
     this.unitOfWork         = unitOfWork;
     this.context            = context;
     this.blogCommentManager = blogCommentManager;
 }
Exemple #14
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;
     }
 }
Exemple #15
0
        public IEnumerable <User> GetAll(QueryParams <User> param)
        {
            try
            {
                param = QueryParams <User> .Validate(param, c => c.UserId, 10);

                using (Container = new ArticleContext())
                {
                    var list   = Container.Users.OrderBy(c => c.UserId).Skip(param.Skip ?? 0).Take(param.Take ?? 0).ToList();
                    var result = Mapper.Map <IEnumerable <Entities.User>, IEnumerable <User> >(list);
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #16
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();
     }
 }
Exemple #17
0
        public IEnumerable <User> GetByPredicate(Expression <Func <User, bool> > predicate, QueryParams <User> param)
        {
            try
            {
                //var currentPredicate = predicate.Convert<Entities.User, User>(mapper);
                var anotherPredicate = Mapper.Map <Expression <Func <User, bool> >, Expression <Func <Entities.User, bool> > >(predicate);
                param = QueryParams <User> .Validate(param, c => c.UserId, 10);

                using (Container = new ArticleContext())
                {
                    var list = Container.Users
                               .OrderBy(c => c.UserId)
                               .Where(anotherPredicate)
                               .Skip(param.Skip ?? 0)
                               .ToList();
                    var result = Mapper.Map <IEnumerable <Entities.User>, IEnumerable <User> >(list);
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
 public LikeService(IGenericRepository <Like> likeRepo, UnitOfWork unitOfWork, ArticleContext context, LikeManager likeManager)
 {
     this.likeRepo    = likeRepo;
     this.unitOfWork  = unitOfWork;
     this.context     = context;
     this.likeManager = likeManager;
 }
        public void SaveArticle()
        {
            ArticleContext context = new ArticleContext();

            context.Articles.Add(new Article {
                ArticleID = 1, Caption = "12", Text = "qwe", UserID = 1
            });
            context.Articles.Add(new Article {
                ArticleID = 2, Caption = "1212", Text = "qwew", UserID = 1
            });
            context.Articles.Add(new Article {
                ArticleID = 3, Caption = "11232", Text = "qwqe", UserID = 1
            });

            Article article = new Article
            {
                ArticleID = 0,
                UserID    = 1,
                Caption   = "cap1",
                Text      = "Sometext",
                Language  = "ru",
                Date      = new DateTime(2018, 11, 12),
                Image     = "someLink",
                Video     = "someLinkForVideo"
            };

            ArticleRepository res = new ArticleRepository();

            res.SaveArticle(article);

            Assert.IsTrue(res.Articles.Count() == 4);
        }
Exemple #20
0
 /// <exception cref="InvalidOperationException" />
 /// <exception cref="NotSupportedException" />
 private void PopulateField(ArticleObject dict, ArticleField field, ArticleContext context)
 {
     if (field is ExtensionArticleField extensionArticleField)
     {
         PopulateExtensionFields(dict, extensionArticleField, context);
     }
     else if (field is MultiArticleField multiArticleField)
     {
         dict[field.FieldName] = multiArticleField
                                 .GetArticles(context.Filter)
                                 .Select(f => ConvertArticle(f, context))
                                 .Where(a => a != null)
                                 .ToArray();
     }
     else if (field is SingleArticleField singleArticleField)
     {
         dict[field.FieldName] = ConvertArticle(singleArticleField.GetItem(context.Filter), context);
     }
     else if (field is PlainArticleField plainArticleField)
     {
         dict[field.FieldName] = ConvertPlainField(plainArticleField);
     }
     else
     {
         throw new NotSupportedException($"Field with type {field.GetType()} is not supported");
     }
 }
Exemple #21
0
        public IEnumerable <Article> GetByTagWithTags(IEnumerable <int> ids, QueryParams <Article> param)
        {
            try
            {
                param = QueryParams <Article> .Validate(param, c => c.ArticleId, 10);

                using (Container = new ArticleContext())
                {
                    var list = Container.Articles
                               .OrderBy(c => c.ArticleId)
                               .Where(c => c.Tags.Count > 0 && !ids.Except(c.Tags.Select(x => x.Id)).Any())
                               .Skip(param.Skip ?? 0)
                               .Take(param.Take ?? 0)
                               .ToList();
                    var result = Mapper.Map <IEnumerable <Entities.Article>, IEnumerable <Article> >(list);
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #22
0
 public AccountController(ArticleContext articleContex, ILogger <InformationController> logger, IPasswordHasher <User> passwordHasher, IJwtPrivider jwtPrivider)
 {
     _articleContext = articleContex;
     _logger         = logger;
     _passwordHasher = passwordHasher;
     _jwtPrivider    = jwtPrivider;
 }
Exemple #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());
            }
        }
Exemple #24
0
 public CommentService(IGenericRepository <Comment> commentRepo, UnitOfWork unitOfWork, ArticleContext context, CommentManager commentManager)
 {
     this.commentRepo    = commentRepo;
     this.unitOfWork     = unitOfWork;
     this.context        = context;
     this.commentManager = commentManager;
 }
Exemple #25
0
        public IEnumerable <ITag> GetAll(QueryParams <ITag> param)
        {
            try
            {
                param = QueryParams <ITag> .Validate(param, c => c.Id, 10);

                using (Container = new ArticleContext())
                {
                    var list   = Container.Tags.OrderBy(c => c.Id).Skip(param.Skip ?? 0).Take(param.Take ?? 0).ToList();
                    var result = Mapper.Map <IEnumerable <Entities.Tag>, IEnumerable <Tag> >(list);
                    //var enumerable = result as IList<Article> ?? result.ToList();
                    //foreach (var article in enumerable)
                    //{
                    //	article.GroupId = article.ArticleGroup.GroupId;
                    //}
                    return(result.OrderBy(param.Order).ToList());
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
 public AppUserService(IGenericRepository <AppUser> userRepo, UnitOfWork unitOfWork, ArticleContext context, AppUserManager userManager)
 {
     this.userRepo    = userRepo;
     this.unitOfWork  = unitOfWork;
     this.context     = context;
     this.userManager = userManager;
 }
Exemple #27
0
 public DataSet GetDataSetBySqlPredicate(string sql, params object[] args)
 {
     using (Container = new ArticleContext())
     {
         var retVal   = new DataSet();
         var sqlConn  = Container.Database.Connection as SqlConnection;
         var sqlQuery = new SqlCommand(sql, sqlConn)
         {
             CommandType = CommandType.Text
         };
         var adapter = new SqlDataAdapter(sqlQuery);
         using (sqlQuery)
         {
             if (args.Any())
             {
                 foreach (var o in args)
                 {
                     var param = new SqlParameter(o.ToString(), o);
                     sqlQuery.Parameters.Add(param);
                 }
             }
             adapter.Fill(retVal);
         }
         return(retVal);
     }
 }
Exemple #28
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }



            using (var scope = app.ApplicationServices.CreateScope())
            {
                ArticleContext context = scope.ServiceProvider.GetRequiredService <ArticleContext>();

                DbObjects.Init(context);
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Comment}/{action=Index}");
            });
        }
Exemple #29
0
        public IEnumerable <IPlan> GetByPredicate(Expression <Func <IPlan, bool> > predicate, QueryParams <IPlan> param)
        {
            try
            {
                param = QueryParams <IPlan> .Validate(param, c => c.Id, 10);

                using (Container = new ArticleContext())
                {
                    var list = Container.Plans.OrderBy(c => c.Id)
                               .Where(predicate)
                               .Skip(param.Skip ?? 0)
                               .Take(param.Take ?? 0)
                               .ToList();
                    var result = Mapper.Map <IEnumerable <Entities.Plan>, IEnumerable <CurrentPlan> >(list.Select(c => c as Plan));
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public IEnumerable <Transaction> GetAll(QueryParams <Transaction> param)
        {
            try
            {
                param = QueryParams <Transaction> .Validate(param, c => c.Id, 10);

                using (Container = new ArticleContext())
                {
                    var list   = Container.TransactionLogs.OrderByDescending(c => c.ActionDateTime).Skip(param.Skip ?? 0).Take(param.Take ?? 0).ToList();
                    var result = Mapper.Map <IEnumerable <Entities.TransactionLog>, IEnumerable <Transaction> >(list);
                    return(result);                    //.OrderBy(param.Order);
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }