public BlogDto GetBlogArticle(int?categoryId = null) { var blogDto = new BlogDto(); var repos = new ArticlesRepository(_context, new LogsRepository(_context)); var blogs = new List <BlogViewModel>(); if (categoryId == null) { blogs = repos.GetArticles().Select(s => new BlogViewModel(s, _currentLang)).ToList(); } else { var category = repos.GetCategory(categoryId.Value); if (category != null) { //ViewBag.BreadCrumb = category.Title; blogs = repos.GetArticlesByCategory(categoryId.Value).Select(s => new BlogViewModel(s, _currentLang)).ToList(); } } var categories = _context.ArticleCategories.Where(w => !w.IsDeleted) .Select(s => new BlogCategoryModel { Id = s.Id, Title = _currentLang == (int)Language.Farsi ? s.Title : s.EnglishTitle }).ToList(); blogDto.Blogs.AddRange(blogs); blogDto.Categories.AddRange(categories); blogDto.RecentBlogs = repos.GetArticles().Select(s => new BlogViewModel(s, _currentLang)).ToList(); return(blogDto); }
static void Main(string[] args) { FluentMapper.Initialize(config => { config.AddMap(new ArticleMap()); }); OnvistaArticlesParsingParameters parserParameters = new OnvistaArticlesParsingParameters(args); ArticlesRepository repository = new ArticlesRepository(); ArticlesParser parser = new ArticlesParser(repository); var newsArticles = parser.ParseArticles(parserParameters); var pendingForSave = newsArticles.Where(x => x.ResultType == ParsingResultType.PendingForSave).ToList(); Console.WriteLine($"{newsArticles.Count} Articles were parsed.{Environment.NewLine}" + $"PendingForSave: {pendingForSave.Count} | " + $"Saved: {newsArticles.Count(x => x.ResultType == ParsingResultType.Saved)} | " + $"Already exists: {newsArticles.Count(x => x.ResultType == ParsingResultType.AlreadyExists)} "); if (pendingForSave.Count > 0) { Console.WriteLine("Saving parser results..."); parser.SaveParsingResults(pendingForSave); Console.WriteLine("Done"); } SaveParsedArticlesToCsv(newsArticles); }
protected void Page_Load(object sender, EventArgs e) { db = new ContentManagementEntities(); rep = new ArticlesRepository(); repCat = new CategoriesRepository(); Authorid = AddArticle.myid; AdminVarmi = AdminLogin.isAdmin; catList = repCat.List(); author = db.Authors.Where(c => c.Id == Authorid).FirstOrDefault(); ArticleId = Convert.ToInt32(Request.QueryString["id"].ToString()); article = db.Articles.Where(c => c.Id == ArticleId).FirstOrDefault(); if (AdminVarmi) { author = article.Authors; } if (IsPostBack) { article.ArticleBody = Request.Form["ArticleBody"].ToString(); article.Title = Request.Form["Title"].ToString(); article.IsVisible = true; article.CreateDate = DateTime.Now; article.CategoryId = Convert.ToInt32(Request.Form["CatType"]); article.Authors.Id = Authorid; rep.Update(article); Response.Redirect("/ReadArticleDetail?id=" + article.Id); } }
protected void Page_Load(object sender, EventArgs e) { if (Session["username"] != null) { db = new ContentManagementEntities(); if (Request.Form["action"] == "save") { SaveToDb(); } id = Convert.ToInt32(Request.QueryString["id"]); if (id != 0) { myid = id; } author = author = db.Authors.Where(c => c.Id == myid).FirstOrDefault(); rep = new ArticlesRepository(); repCat = new CategoriesRepository(); repAuthor = new AuthorsRepository(); articleList = rep.List(); catList = repCat.List(); authorsList = repAuthor.List(); } else { Response.Redirect("/AuthorLogin"); } }
public void DeleteArticle_Valid_Id() { using (TransactionScope transaction = new TransactionScope()) { articleRepository = new ArticlesRepository(); int count = articleRepository.GetAllArticles().Count(); //Count articles pre-editting of existing article SMCC.Models.Article originalArticle = new SMCC.Models.Article(); SMCC.Models.Article deleteArticle = new SMCC.Models.Article(); List <SMCC.Models.Article> existArticles = new List <SMCC.Models.Article>(); try { //Set your controller ControllerContext with fake context articleController.ControllerContext = MockContext().Object; originalArticle = articleRepository.GetArticle(1); var result = articleController.Delete(1) as ViewResult; deleteArticle = (SMCC.Models.Article)result.ViewData.Model; articleController.DeleteConfirmed(deleteArticle.ArticleId); } finally { articleRepository = new ArticlesRepository(); existArticles = articleRepository.GetAllArticles().ToList(); Assert.AreEqual(count - 1, existArticles.Count()); //Record count should be deducted by 1 after deletion CollectionAssert.DoesNotContain(existArticles, originalArticle); // Article should no longer be present in db. } } }
public ArticlesController( ArticlesRepository articles, UserBlogsRepository blogsRepository) { this.articlesRepository = articles; this.blogsRepository = blogsRepository; }
public ArticleMutation(ArticlesRepository repo) { FieldAsync <ArticleType>( "createArticle", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <ArticleTypeInput> > { Name = "article" }), resolve: async context => { var article = context.GetArgument <Article>("article"); return(await context.TryAsyncResolve( async c => await repo.AddArticle(article))); } ); FieldAsync <ArticleType>( "removeArticle", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > { Name = "id" }), resolve: async context => { var id = context.GetArgument <string>("id"); return(await context.TryAsyncResolve( async _ => await repo.RemoveArticle(Guid.Parse((ReadOnlySpan <char>)id)) )); } ); }
protected void Page_Load(object sender, EventArgs e) { db = new ContentManagementEntities(); authorid = AddArticle.myid; author = db.Authors.Where(c => c.Id == authorid).FirstOrDefault(); rep = new ArticlesRepository(); repAutors = new AuthorsRepository(); repCat = new CategoriesRepository(); articleList = rep.List(); isonclick = false; if (IsPostBack) { isonclick = true; } if (isonclick) { articleListFilter = rep.FilterList(Title.Value, Request.Form["CatType"], Request.Form["Autors"], ArticleBody.Value); } else { articleListFilter = rep.List(); } catList = repCat.List(); authorList = repAutors.List(); }
public void AddArticle_AddsArticle_WhenValidData() { using (var ctx = ContextUtil.GetContext()) { var repo = new ArticlesRepository(ctx); var article = new ArticleDto { Title = "The empire actually strikes back!?", Body = "[Insert something funny here]", Tags = new string[] { "star wars", "light side", "dark side", "dark side" } }; var result = repo.AddArticle(article).GetAwaiter().GetResult(); Assert.AreEqual("The empire actually strikes back!?", result.Title); Assert.AreEqual("[Insert something funny here]", result.Body); new List <string>() { "Star Wars", "Light Side", "Dark Side" }.Select(x => { var tag = result.Tags.First(y => x == y); Assert.AreEqual(x, tag); return(tag); }); // Give it two minutes Assert.IsTrue(result.Date > DateTime.UtcNow.AddMinutes(-1) && result.Date < DateTime.UtcNow.AddMinutes(1)); } }
public async Task GetAsync_PriceFilteredAndOrdered() { VolatileCoreBusinessDataset store = new VolatileCoreBusinessDataset(); Mock <ICoreBusinessContext> context = new Mock <ICoreBusinessContext>(); Mock <ArticlesRepository> mockArticleRepository = new Mock <ArticlesRepository>(context.Object); mockArticleRepository.Setup(r => r.GetAsync(It.IsAny <Expression <Func <Article, bool> > >(), It.IsAny <Func <IQueryable <Article>, IOrderedQueryable <Article> > >(), string.Empty)) .Returns((Expression <Func <Article, bool> > filter, Func <IQueryable <Article>, IOrderedQueryable <Article> > orderBy, string includeProperties) => { var filtered = store.Articles.Where(filter.Compile()).AsQueryable(); var ordered = orderBy.Invoke(filtered); return(Task.FromResult(ordered.AsEnumerable())); }); this.articlesRepository = mockArticleRepository.Object; var result = await this.articlesRepository.GetAsync(filter : a => a.Price > 100m, orderBy : q => q.OrderByDescending(a => a.Price)); Assert.AreEqual(4, result.Count()); Assert.AreEqual(150m, result.Last().Price); Assert.AreEqual(1000.0m, result.First().Price); }
public void CreateArticle_Null_Content_Invalid() { using (TransactionScope transaction = new TransactionScope()) { articleRepository = new ArticlesRepository(); int count = articleRepository.GetAllArticles().Count(); //Count articles pre-creation of new article SMCC.Models.Article newArticle = new SMCC.Models.Article(); SMCC.Models.Article createdArticle = new SMCC.Models.Article(); List <SMCC.Models.Article> existArticles = new List <SMCC.Models.Article>(); try { //Set your controller ControllerContext with fake context articleController.ControllerContext = MockContext().Object; newArticle.Title = "A"; newArticle.Text = null; articleController.Create(newArticle); } finally { articleRepository = new ArticlesRepository(); existArticles = articleRepository.GetAllArticles().ToList(); createdArticle = articleRepository.GetArticle(newArticle.ArticleId); Assert.AreEqual(count, existArticles.Count()); CollectionAssert.DoesNotContain(existArticles, createdArticle); } } }
//Searching And Paging // GET: Articles public ActionResult Index(string searchString, string currentFilter, int?page) { ArticlesRepository ArticlesRepo = new ArticlesRepository(); if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.currentFilter = searchString; var articles = from posts in ArticlesRepo.GetAllArticles() select posts; if (!String.IsNullOrEmpty(searchString)) { articles = articles.Where(search => search.Title.Contains(searchString)); } int pageSize = 3; int pageNumber = (page ?? 1); return(View(articles.ToPagedList(pageNumber, pageSize))); //return View(ArticlesRepo.GetAllArticles()); }
static async Task TestRepo() { var repo = new ArticlesRepository("Articles"); // Example with Print Baked into the Object itself List <Articles> articles = new List <Articles>(); articles = (await repo.GetAllAsync()).ToList(); TestTool.PrintSuccess("Got {0} row from Articles\n", articles.Count()); articles.First().PrintKeys(); articles.ForEach(article => article.Print()); // var repoEmployees = new EmployeesRepository("Employees"); List <Employees> employees = (await repoEmployees.GetAllAsync()).ToList(); TestTool.PrintSuccess("Got {0} row from Employees\n", employees.Count()); Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\n", "ID", "Name", "LastName", "Email", "Password"); employees.ForEach(employee => Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\n", employee.ID, employee.Name, employee.LastName, employee.Email, new string('*', employee.Password.Length))); // var repoIngredients = new IngredientsRepository("Ingredients"); var ingredients = (await repoIngredients.GetAllAsync()).ToList(); TestTool.PrintSuccess("Got {0} row from Ingredients\n", employees.Count()); Console.Write("{0}\t{1}\t{2}\n", "ID", "Name", "Price"); ingredients.ForEach(ingredient => Console.Write("{0}\t{1}\t{2}\n", ingredient.ID, ingredient.Name, ingredient.Price)); // var repoOrders = new OrdersRepository("Orders"); List <Orders> orders = (await repoOrders.GetAllAsync()).ToList(); TestTool.PrintSuccess("Got {0} row from Orders\n", orders.Count()); Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\n", "ID", "TimeCreated", "Orderstatus", "Price", "CustomerID"); orders.ForEach(order => Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\n", order.ID, order.TimeCreated, order.Orderstatus, order.Price, order.CustomerID)); //Orders order = (await repoOrders.GetAsync(4)); //await repoOrders.UpdateAsync(new Orders() {ID = 12, Orderstatus = 0, Price = 124, CustomerID = 1 }); //await repoIngredients.InsertCustomIngredientsAsync(orders.First(), articles.First(), articles.First().Ingredients); //Orders order = orders.First() ; //List<Articles> tempArticles = articles.GetRange(0, 2); //await repoOrders.MakeOrderAsync(order, tempArticles); //List<Articles> orderListArticles = (await repo.GetAllAsync(order)).ToList(); //foreach (var item in orderListArticles) //{ // Console.WriteLine(item.Name + " " + item.Type); // foreach (var item2 in item.Ingredients) // { // Console.Write(item2.Name.Trim() + ", "); // } //} //articles[0].ID = 71; //await General.articlesRepo.UpdateAsync(articles[0]); }
public IActionResult Index([FromServices] ArticlesRepository articlesRep, string searchBy) { var articles = articlesRep.GetArticlesByTitleAndTag(searchBy); ViewBag.SearchBy = searchBy; return(View(articles)); }
public UnitOfWork(OrdersDBContext context) { Context = context; Orders = new OrdersRepository(context); Statuses = new StatusesRepository(context); Adresses = new AdressesRepository(context); Articles = new ArticlesRepository(context); Payments = new PaymentsRepository(context); }
public void GetArticle_ReturnsNull_WhenArticleDoesntExist() { using (var ctx = ContextUtil.GetContext()) { var repo = new ArticlesRepository(ctx); var result = repo.GetArticle(1).GetAwaiter().GetResult(); Assert.IsNull(result); } }
public BlogsController( UserBlogsRepository blogsRepository, UsersRepository usersRepository, ArticlesRepository articlesRepository, DeleteBlogTransaction deleteBlogTransaction) { this.blogsRepository = blogsRepository; this.usersRepository = usersRepository; this.articlesRepository = articlesRepository; this.deleteBlogTransaction = deleteBlogTransaction; }
public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; string contentRootPath = _hostingEnvironment.ContentRootPath; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var enc1251 = Encoding.GetEncoding(1251); var JSON = System.IO.File.ReadAllText(contentRootPath + "/Content/dictionary.json", enc1251); _articlesRepository = new ArticlesRepository(JSON); }
public void DetailsArticle_Existing_Id_Valid() { articleRepository = new ArticlesRepository(); SMCC.Models.Article expectedArticle = articleRepository.GetArticle(1); var result = articleController.Details(1) as ViewResult; SMCC.Models.Article actualArticle = (SMCC.Models.Article)result.ViewData.Model; Assert.IsTrue(AssertSameArticles(expectedArticle, actualArticle)); }
public IActionResult Index([FromServices] ProjectsRepository projRep, [FromServices] ArticlesRepository articleRep) { var projects = projRep.GetProjectList(); var articles = articleRep.Articles; ViewBag.Projects = projects; ViewBag.Articles = articles; return(View()); }
private void Button6_Click(object sender, EventArgs e) { richTextBox1.Clear(); SellersRepository sellRepo = SellersRepository.getInstance(); ArticlesRepository artRepo = ArticlesRepository.getInstance(); Seller s = (Seller)sellRepo.getEntityById(1); richTextBox1.Text = s.Name; }
public IHttpActionResult Read(string id) { var article = ArticlesRepository.Get(id); if (article != null) { return(Ok(article)); } else { return(NotFound()); } }
public ActionResult Edit(int id, ArticlesModel Article) { try { // TODO: Add update logic here ArticlesRepository ArticleRepo = new ArticlesRepository(); ArticleRepo.Update(Article); return(RedirectToAction("Index")); } catch { return(View()); } }
public async Task GetByIdAsync_DoesntExist() { VolatileCoreBusinessDataset store = new VolatileCoreBusinessDataset(); Mock <ICoreBusinessContext> context = new Mock <ICoreBusinessContext>(); Mock <ArticlesRepository> mockArticleRepository = new Mock <ArticlesRepository>(context.Object); mockArticleRepository.Setup(r => r.GetByIdAsync(It.IsNotIn <int>(1, 2, 3, 4, 5, 6))) .Returns <int>(id => Task.FromResult <Article>(null)); this.articlesRepository = mockArticleRepository.Object; Article article = await this.articlesRepository.GetByIdAsync(10); Assert.AreEqual(null, article); }
public void GetById_DoesntExist() { VolatileCoreBusinessDataset store = new VolatileCoreBusinessDataset(); Mock <ICoreBusinessContext> context = new Mock <ICoreBusinessContext>(); Mock <ArticlesRepository> mockArticleRepository = new Mock <ArticlesRepository>(context.Object); mockArticleRepository.Setup(r => r.GetById(It.IsNotIn <int>(1, 2, 3, 4, 5, 6))) .Returns <Article>(null); this.articlesRepository = mockArticleRepository.Object; Article article = this.articlesRepository.GetById(10); Assert.AreEqual(null, article); }
public SiteDataService(ILogger <SiteDataService> logger, IConfiguration configuration, ApplicationDbContext context, CategoryRepository categoryRepository, ServicesRepository servicesRepository, ArticlesRepository articlesRepository, PartnerRepository partnerRepository, SubCategoryRepository subCategoryRepository, IgnoresRepository ignoresRepository) { _logger = logger; _configuration = configuration; _context = context; _categoryRepository = categoryRepository; _servicesRepository = servicesRepository; _articlesRepository = articlesRepository; _partnerRepository = partnerRepository; _subCategoryRepository = subCategoryRepository; _ignoresRepository = ignoresRepository; }
public IHttpActionResult Create(string id, string name, string content) { var exists = ArticlesRepository.Get(id) != null; if (exists) { return(StatusCode(HttpStatusCode.Conflict)); } else { ArticlesRepository.Add(id, name, content); return(Ok()); } }
private void Button1_Click(object sender, EventArgs e) { richTextBox1.Clear(); ArticlesRepository artRepo = ArticlesRepository.getInstance(); EntityList list = artRepo.getList(); Article[] entities = (Article[])list.fetch(); foreach (Article ar in entities) { richTextBox1.Text += ar.Name + " " + ar.Id + "\n"; } }
public async Task GetAsync_MinimumPriceFiltered() { VolatileCoreBusinessDataset store = new VolatileCoreBusinessDataset(); Mock <ICoreBusinessContext> context = new Mock <ICoreBusinessContext>(); Mock <ArticlesRepository> mockArticleRepository = new Mock <ArticlesRepository>(context.Object); mockArticleRepository.Setup(r => r.GetAsync(It.IsAny <Expression <Func <Article, bool> > >(), null, string.Empty)) .Returns((Expression <Func <Article, bool> > filter, Func <IQueryable <Article>, IOrderedQueryable <Article> > orderBy, string includeProperties) => Task.FromResult(store.Articles.Where(filter.Compile()))); this.articlesRepository = mockArticleRepository.Object; var result = await this.articlesRepository.GetAsync(filter : a => a.Price > 100m); Assert.AreEqual(4, result.Count()); }
public void Get_Filtered() { VolatileCoreBusinessDataset store = new VolatileCoreBusinessDataset(); Mock <ICoreBusinessContext> context = new Mock <ICoreBusinessContext>(); Mock <ArticlesRepository> mockArticleRepository = new Mock <ArticlesRepository>(context.Object); mockArticleRepository.Setup(r => r.Get(It.IsAny <Expression <Func <Article, bool> > >(), null, string.Empty)) .Returns((Expression <Func <Article, bool> > filter, Func <IQueryable <Article>, IOrderedQueryable <Article> > orderBy, string includeProperties) => store.Articles.Where(filter.Compile())); this.articlesRepository = mockArticleRepository.Object; var result = this.articlesRepository.Get(a => a.IdCategory == 1); Assert.AreEqual(3, result.Count()); }