public async Task ActionGetAllShouldReturnStatusCodeOkAndAllNewsItems()
        {
            //Arrange
            const string Test = "Test";

            var dbOptions = new DbContextOptionsBuilder <NewsDbContext>()
                            .UseInMemoryDatabase("NewsDb")
                            .Options;

            var db             = new NewsDbContext(dbOptions);
            var newsService    = new NewsService(db);
            var userController = new NewsController(newsService);

            var news = new News
            {
                Id          = 1,
                Title       = Test,
                Content     = "Test content",
                PublishDate = DateTime.UtcNow
            };

            await db.News.AddAsync(news);

            await db.SaveChangesAsync();

            //Act
            var result = await userController.GetAll();

            //Assert
            result
            .Should()
            .BeOfType <OkObjectResult>()
            .Which.Value.As <NewsFullDetailsServiceModel>();
        }
Example #2
0
 public Repository(NewsDbContext newsDbContext, UserManager <User> userManager,
                   IUnitOfWork unitOfWork)
 {
     _newsDbContext = newsDbContext;
     _userManager   = userManager;
     _unitOfWork    = unitOfWork;
 }
Example #3
0
 private static void AddReminders(NewsDbContext context)
 {
     context.Reminders.Add(new Reminder {
         NewsId = 101, Schedule = DateTime.Now.AddDays(5)
     });
     context.SaveChanges();
 }
 private static void UpdateNewsContent(News firstNews, NewsDbContext context)
 {
     Console.WriteLine("Text from DB: " + firstNews.Content);
     Console.Write("Enter the corrected text: ");
     string newContent = Console.ReadLine();
     firstNews.Content = newContent;
 }
Example #5
0
        public void GetBugsShouldReturnAllBugs()
        {
            DbContext = new NewsDbContext();
            this.data = new NewsData(DbContext);
            // Arrange -> prapare the objects

            this.data.News.Add(new NewsItem
            {
                Title       = "Test",
                Content     = "Test",
                PublishDate = DateTime.Now
            });

            this.data.News.Add(new NewsItem
            {
                Title       = ";sdka;skladfh;aklsj kljoidflkjal",
                Content     = "Test;Test;Test;Test",
                PublishDate = DateTime.Now.AddDays(-1)
            });
            this.data.SaveChanges();

            // Act -> perform some logic
            var news = this.data.News.All().Count();

            // Assert -> validate the results
            Assert.AreEqual(2, news);
        }
Example #6
0
        public void DbInitialization()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <NewsDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            this.db = new NewsDbContext(options);
            var categoryService = new CategoryService(db);

            var author = new User()
            {
                Id = "2", UserName = "******"
            };
            var category1 = new Category()
            {
                Id = 1, Name = "Movies"
            };
            var category2 = new Category()
            {
                Id = 2, Name = "Fashion"
            };
            var category3 = new Category()
            {
                Id = 3, Name = "Travel"
            };

            db.Categories.AddRange(category1, category2, category3);
            db.SaveChanges();
        }
Example #7
0
        public static void SeedUsers(UserManager <User> userManager, RoleManager <Role> roleManager,
                                     NewsDbContext newsDbContext)
        {
            if (userManager.Users.Any())
            {
                return;
            }

            var roles = new List <Role>()
            {
                new Role()
                {
                    Name = Constants.RoleNameAdmin
                },
                new Role()
                {
                    Name = Constants.RoleNameNormalUser
                }
            };

            roles.ForEach(role => roleManager.CreateAsync(role).Wait());

            var adminUser = new User()
            {
                UserName = "******",
                Country  = Constants.UnitedStates(),
                Language = Constants.English()
            };

            userManager.CreateAsync(adminUser, "Password*123").Wait();
            userManager.AddToRoleAsync(adminUser, Constants.RoleNameAdmin).Wait();
        }
 public static void AssemblyInit(TestContext context)
 {
     using (var newsDbContext = new NewsDbContext())
     {
         newsDbContext.Database.CreateIfNotExists();
     }
 }
        public void Init()
        {
            this.dbcontext = new NewsDbContext();
            this.dbcontext.Database.CreateIfNotExists();

            this.transactionScope = new TransactionScope();
        }
        public void DbInitialization()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <NewsDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            this.db = new NewsDbContext(options);
            var articleService = new ArticleService(db);

            var author = new User()
            {
                Id = "2", UserName = "******"
            };
            var category = new Category()
            {
                Id = 1, Name = "TestCategory"
            };

            var article1 = new Article()
            {
                Id = 1, Title = "Test1", Author = author, Category = category
            };
            var article2 = new Article()
            {
                Id = 2, Title = "Test2", Author = author, Category = category
            };
            var article3 = new Article()
            {
                Id = 3, Title = "Test3", Author = author, Category = category
            };

            db.Articles.AddRange(article1, article2, article3);
            db.SaveChanges();
        }
 public static void AssemblyInit(TestContext context)
 {
     using (var newsDbContext = new NewsDbContext())
     {
         newsDbContext.Database.CreateIfNotExists();
     }
 }
Example #12
0
        public void TestAddValidNews()
        {
            ClearNews();
            var news = new News {
                Title = "Zaglavie", Content = "tralala123"
            };
            var postContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("title", news.Title),
                new KeyValuePair <string, string>("content", news.Content)
            });

            var httpResponse = this.httpClient.PostAsync("/api/news", postContent).Result;

            Assert.AreEqual(HttpStatusCode.Created, httpResponse.StatusCode);
            Assert.IsNotNull(httpResponse.Headers.Location);

            var returnedNews = httpResponse.Content.ReadAsAsync <News>().Result;

            Assert.IsTrue(returnedNews.Id != 0);
            Assert.AreEqual(news.Title, returnedNews.Title);
            Assert.AreEqual(news.Content, returnedNews.Content);
            Assert.AreEqual(news.PublishDate.ToString(), returnedNews.PublishDate.ToString());

            using (var dbContext = new NewsDbContext())
            {
                var newsFromDb = dbContext.News.FirstOrDefault();
                Assert.IsNotNull(newsFromDb);
                Assert.AreEqual(returnedNews.Id, newsFromDb.Id);
                Assert.AreEqual(returnedNews.Title, newsFromDb.Title);
                Assert.AreEqual(returnedNews.PublishDate.ToString(), newsFromDb.PublishDate.ToString());
                Assert.AreEqual(returnedNews.Content, newsFromDb.Content);
            }
        }
Example #13
0
 public NewsService(
     NewsDbContext context,
     StatisticNewsService statisticNewsService)
 {
     this.context = context;
     this.statisticNewsService = statisticNewsService;
 }
Example #14
0
        public async Task InvokeAsync(HttpContext httpcontext, NewsDbContext context)
        {
            var authHeader = httpcontext
                             .Request
                             .Headers
                             .ContainsKey("Authorization");

            if (authHeader)
            {
                var username = httpcontext
                               .User
                               .GetUserName();

                var user = await context
                           .Users
                           .FirstOrDefaultAsync(u => u.UserName == username);

                var profile = await context
                              .Profiles
                              .FirstOrDefaultAsync(p => p.UserId == user.Id && !p.isBaned);

                if (profile != null)
                {
                    profile.LastActiveOn = DateTime.Now;
                    context.Profiles.Update(profile);
                    await context.SaveChangesAsync();
                }
            }
            await next.Invoke(httpcontext);
        }
Example #15
0
        public void TestListAll()
        {
            ClearNews();
            var news = new[]
            {
                new News {
                    Title = "Zaglavie", Content = "dadadada"
                },
                new News {
                    Title = "Asdjoqwe", Content = "asodojk"
                }
            };

            using (var dbContext = new NewsDbContext())
            {
                dbContext.News.AddRange(news);
                dbContext.SaveChanges();
            }

            var httpResponse = this.httpClient.GetAsync("/api/news").Result;
            var returnedNews = httpResponse.Content.ReadAsAsync <List <News> >().Result;

            Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);
            Assert.AreEqual(httpResponse.Content.Headers.ContentType.MediaType, "application/json");
            Assert.AreEqual(2, returnedNews.Count);
            for (var i = 0; i < returnedNews.Count; i++)
            {
                Assert.AreEqual(returnedNews[i].Content, news[i].Content);
                Assert.AreEqual(returnedNews[i].Title, news[i].Title);
                Assert.AreEqual(returnedNews[i].PublishDate.ToString(), news[i].PublishDate.ToString());
                Assert.AreEqual(returnedNews[i].UserId, news[i].UserId);
            }
        }
        public void AddNews_WhenNewsItemIsValid_ShouldAddtoDB()
        {
            //Arrange
            var context = new NewsDbContext();
            var data    = new NewsData(context);
            var news    = new NewsItem
            {
                Title       = "Title1",
                Content     = "News content",
                PublishDate = new DateTime(2000, 12, 1, 14, 01, 55)
            };

            //Act
            data.News.Add(news);
            data.SaveChanges();

            //Assert
            var newsFromDb = data.News.Find(news.Id);

            Assert.IsNotNull(newsFromDb, "News is not added to database");
            Assert.AreNotEqual(newsFromDb.Id, 0, "News has 0 for Id");
            Assert.AreEqual(news.Title, newsFromDb.Title, "Title is not corect");
            Assert.AreEqual(news.Content, newsFromDb.Content, "Content is not corect");
            Assert.AreEqual(news.PublishDate.ToString(), newsFromDb.PublishDate.ToString(), "Date is not corect");
        }
Example #17
0
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public async Task <List <NewsSource> > UpdateNewsSourcesAsync(bool force)
        {
            // Wait for the old update to finish first:
            if (updateTask is null || updateTask.IsCompleted)
            {
                updateTask = Task.Run(async() =>
                {
                    List <NewsSource> newsSources;
                    if (!force && CacheDbContext.IsCacheEntryValid(NEWS_SOURCES_URI.ToString()))
                    {
                        Logger.Info("No need to fetch news sources. Cache is still valid.");
                        using (NewsDbContext ctx = new NewsDbContext())
                        {
                            newsSources = ctx.NewsSources.ToList();
                        }
                    }
                    else
                    {
                        newsSources = await DownloadNewsSourcesAsync();
                        if (!(newsSources is null))
                        {
                            using (NewsDbContext ctx = new NewsDbContext())
                            {
                                ctx.RemoveRange(ctx.NewsSources);
                                ctx.AddRange(newsSources);
                            }
                            CacheDbContext.UpdateCacheEntry(NEWS_SOURCES_URI.ToString(), DateTime.Now.Add(MAX_TIME_IN_CACHE));
                            return(newsSources);
                        }
                    }
                    return(new List <NewsSource>());
                });
            }
            return(await updateTask.ConfAwaitFalse());
        }
        public async Task <IHttpActionResult> Post(CreateAuthorViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var ctx = new NewsDbContext())
            {
                var author = new Author()
                {
                    Name = model.Name
                };

                ctx.Authors.Add(author);
                await ctx.SaveChangesAsync();

                var data = new AuthorViewModel()
                {
                    Id   = author.Id,
                    Name = author.Name
                };

                return(Created(new Uri(Request.RequestUri + "api/authors" + data.Id), data));
            }
        }
        public void ListAllNews_WhenAddedTwoNews_ShouldTwoNewsInDB()
        {
            //Arrange
            var context = new NewsDbContext();
            var data    = new NewsData(context);
            var news1   = new NewsItem
            {
                Title       = "news 1",
                Content     = "News content",
                PublishDate = new DateTime(2000, 12, 1, 14, 01, 55)
            };

            var news2 = new NewsItem
            {
                Title       = "news 2",
                Content     = "News content2",
                PublishDate = new DateTime(2000, 12, 1, 14, 01, 55)
            };

            data.News.Add(news1);
            data.News.Add(news2);
            data.SaveChanges();

            //Act
            var newsItems = data.News.All().ToList();

            Assert.AreEqual(2, newsItems.Count);
            Assert.AreEqual(news1.Title, newsItems[0].Title, "Title is not corect");
            Assert.AreEqual(news1.Content, newsItems[0].Content, "Content is not corect");
            Assert.AreEqual(news1.PublishDate.ToString(), newsItems[0].PublishDate.ToString(), "Date is not corect");
        }
Example #20
0
        public static void MakeParalelUpdate()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<NewsDbContext, Configuration>());
            var context = new NewsDbContext();
            var firstNews = context.News.FirstOrDefault();

            Console.WriteLine("First news current content: " + firstNews.Content);
            Console.WriteLine("Enter the new text: ");

            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    var newText = Console.ReadLine();
                    firstNews.Content = newText;
                    context.SaveChanges();
                    transaction.Commit();

                    Console.WriteLine("Update successful");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    Console.WriteLine("Conflict occured! \nThe transcation has been rolled back!");
                    Console.WriteLine(ex.Message);
                    MakeParalelUpdate();
                }
            }
        }
Example #21
0
 private static void AddUsers(NewsDbContext context)
 {
     context.Users.Add(new UserProfile {
         UserId = "Jack", FirstName = "Jackson", LastName = "James", Contact = "9812345670", Email = "*****@*****.**", CreatedAt = DateTime.Now
     });
     context.SaveChanges();
 }
Example #22
0
        public void DbInitialization()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <NewsDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            this.db = new NewsDbContext(options);
            var userService = new UserService(db);

            var user1 = new User()
            {
                Id = "1", UserName = "******"
            };
            var user2 = new User()
            {
                Id = "2", UserName = "******"
            };
            var user3 = new User()
            {
                Id = "3", UserName = "******"
            };
            var user4 = new User()
            {
                Id = "4", UserName = "******"
            };


            db.Users.AddRange(user1, user2, user3, user4);
            db.SaveChanges();
        }
Example #23
0
        public void TestModifyInvalidNews()
        {
            ClearNews();
            var news = new News {
                Title = "Zaglavie", Content = "tralala123"
            };

            using (var dbContext = new NewsDbContext())
            {
                dbContext.News.Add(news);
                dbContext.SaveChanges();
            }

            var postContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("content", "No Title")
            });

            var httpResponse = this.httpClient.PutAsync("/api/news/" + news.Id, postContent).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, httpResponse.StatusCode);

            using (var dbContext = new NewsDbContext())
            {
                var newsFromDb = dbContext.News.FirstOrDefault();
                Assert.IsNotNull(newsFromDb);
                Assert.AreEqual(news.Title, newsFromDb.Title);
                Assert.AreEqual(news.Content, newsFromDb.Content);
            }
        }
 public List <News> GetList()
 {
     using (var ctx = new NewsDbContext())
     {
         var result = ctx.News.ToList();
         return(result);
     }
 }
 public CategoryController(IArticleService articleService,
                           ICategoryService categoryService, NewsDbContext dbContext, IMapper mapper)
 {
     this.articleService  = articleService;
     this.categoryService = categoryService;
     DbContext            = dbContext;
     Mapper = mapper;
 }
 public List <News> GetList(string exactWord)
 {
     using (var ctx = new NewsDbContext())
     {
         var result = ctx.News.Where(a => a.Title == exactWord).ToList();
         return(result);
     }
 }
Example #27
0
        public static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<NewsDbContext, Configuration>());
            var database = new NewsDbContext();

            // Problem 2. Concurrent Updates (Console App)
            ParalelUpdates.MakeParalelUpdate();
        }
Example #28
0
 private static void ClearUsers()
 {
     using (var dbContext = new NewsDbContext())
     {
         dbContext.Users.Delete();
         dbContext.SaveChanges();
     }
 }
Example #29
0
 public SectionService(
     NewsDbContext context,
     INewsService newsService
     )
 {
     this.context     = context;
     this.newsService = newsService;
 }
 public AccountController(NewsDbContext db,
                          UserManager <User> userManager,
                          SignInManager <User> signInManager)
 {
     _db            = db;
     _signInManager = signInManager;
     _userManager   = userManager;
 }
 public void Delete(News news)
 {
     using (var ctx = new NewsDbContext())
     {
         ctx.News.Remove(news);
         ctx.SaveChanges();
     }
 }
 public void Update(News news)
 {
     using (var ctx = new NewsDbContext())
     {
         ctx.News.Update(news);
         ctx.SaveChanges();
     }
 }
 public News Get(int id)
 {
     using (var ctx = new NewsDbContext())
     {
         var result = ctx.News.FirstOrDefault(f => f.Id == id);
         return(result);
     }
 }
        public List <News> GetListBySearch(string searchWord)
        {
            using (var ctx = new NewsDbContext())
            {
                var result = ctx.News.Where(a => a.Content.Contains(searchWord)).ToList();
//                ctx.News.Where(e => EF.Functions.Like(e.Title, "%f%")).ToList();
                return(result);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if(this.ReaderId == string.Empty)
            {
                this.content.Visible = false;
                this.LikesLiteral.Text = db.Articles.Find(int.Parse(this.ArticleId)).Likes.Sum(l => l.Value).ToString();
            }

            this.db = new NewsDbContext();
        }
        public static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<NewsDbContext, Configuration>());
            Console.WriteLine("Application started");

            var contextFirstUser = new NewsDbContext();
            var firstNews = contextFirstUser.News.FirstOrDefault();
            bool running = true;

            do
            {
                if (firstNews != null)
                {
                    UpdateNewsContent(firstNews, contextFirstUser);

                    var contextSecondUser = new NewsDbContext();
                    firstNews = contextSecondUser.News.FirstOrDefault();
                    UpdateNewsContent(firstNews, contextSecondUser);
                    contextFirstUser.SaveChanges();
                    try
                    {
                        contextSecondUser.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        Console.WriteLine("Conflict! Text from DB: {0}. Enter the corrected text:", firstNews.Content);
                        Console.WriteLine(ex.Message);
                        UpdateNewsContent(firstNews, contextSecondUser);
                    }
                }
                else
                {
                    Console.WriteLine("Sorry, no news yet!");
                }
            } while (!running);
        }
 public Categories()
 {
     this.db = new NewsDbContext();
 }
 public NewsRepository(NewsDbContext context)
 {
     _context = context;
 }
 public BasePage()
 {
     this.dbContext = new NewsDbContext();
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     this.db = new NewsDbContext();
 }
 public EditCategories()
 {
     this.dbContext = new NewsDbContext();
 }
 public IEnumerable<Category> Categories_GetData()
 {
     var localDb = new NewsDbContext();
     return localDb.Categories.OrderBy(b => b.Name).ToList();
 }
 public EditArticles()
 {
     this.dbContext = new NewsDbContext();
 }
 public ArticleDetails()
 {
     this.dbContext = new NewsDbContext();
 }
 public Home()
 {
     this.dbContext = new NewsDbContext();
 }
Example #46
0
 public Articles()
 {
     this.db = new NewsDbContext();
 }
Example #47
0
 public News()
 {
     this.db = new NewsDbContext();
 }