public void Create5NewPageSuccessfulTest() { using (UnitOfWork uow = new UnitOfWork()) { PageRepository pr = new PageRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); Blog.Model.Domain.Entities.Blog b = new Blog.Model.Domain.Entities.Blog("Nombe blog", "Desc blog"); Category c = new Category("Categoria 1", "Desc 1"); Author a = new Author("Nome autore", "Cognome autore", Convert.ToDateTime("27/12/1987"), "*****@*****.**", true, "pass", b); Page p1 = new Page("Nome pagina 1", "descr pagine", DateTime.Now, "test", a, b, c); Page p2 = new Page("Nome pagina 2", "descr pagine", DateTime.Now, "test", a, b, c); Page p3 = new Page("Nome pagina 3", "descr pagine", DateTime.Now, "test", a, b, c); Page p4 = new Page("Nome pagina 4", "descr pagine", DateTime.Now, "test", a, b, c); Page p5 = new Page("Nome pagina 5", "descr pagine", DateTime.Now, "test", a, b, c); br.Save(b); pr.Save(p1); pr.Save(p2); pr.Save(p3); pr.Save(p4); pr.Save(p5); uow.Commit(); } }
public ActionResult Index() { try { using (UnitOfWork uow = new UnitOfWork()) { BlogRepository br = new BlogRepository(uow.Current); try { if (br.FindAll().Count > 0) { //Vai alla pagina di gestione return RedirectToAction("Index", "Manage"); } else return View(); } catch (Exception ex) { //Il database non esiste, lo inizializzo SessionManager.Instance.BuildSchema(); return View(); } } } catch (Exception ex) { return Error(ex); } }
public void Setup() { var blog = new Blog() { Title = "My Blog" }; BlogRepository repo = new BlogRepository(); repo.Save(blog); }
public void ShouldAllowGettingASetOfObjectGenericallu() { //Arrange IDbContext mockContext = MockRepository.GenerateMock<IDbContext>(); IBlogRepository repository = new BlogRepository(new UnitOfWork(mockContext)); //Act var items = repository.Set<Blog>(); //Assert mockContext.AssertWasCalled(x => x.Find<Blog>()); }
public virtual async Task <PagedResultDto <BlogDto> > GetListAsync(BlogGetListInput input) { var totalCount = await BlogRepository.GetCountAsync(input.Filter); var blogs = await BlogRepository.GetListAsync( input.Filter, input.Sorting, input.MaxResultCount, input.SkipCount); return(new PagedResultDto <BlogDto>(totalCount, ObjectMapper.Map <List <Blog>, List <BlogDto> >(blogs))); }
public virtual async Task <BlogDto> UpdateAsync(Guid id, UpdateBlogDto input) { var blog = await BlogRepository.GetAsync(id); blog = await BlogManager.UpdateAsync(blog, input.Name, input.Slug); blog.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp); await BlogRepository.UpdateAsync(blog); return(ObjectMapper.Map <Blog, BlogDto>(blog)); }
public UnitOfWork(string connectionString) { _context = new ApplicationContext(connectionString); ArticleRepository = new ArticleRepository(_context); BlogRepository = new BlogRepository(_context); CommentRepository = new CommentRepository(_context); UserProfileRepository = new ProfileRepository(_context); TagRepository = new TagRepository(_context); RoleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(_context)); UserManager = new ApplicationUserManager(new UserStore <ApplicationUser>(_context)); }
public async Task <IViewComponentResult> InvokeAsync() { Dictionary <string, int> model = null; await Task.Run(() => { model = BlogRepository.GetTags(Blog.Id); }); // ReSharper disable once Mvc.ViewComponentViewNotResolved return(View(model)); }
/// <summary> /// 更新博客信息 /// </summary> /// <param name="dtos">包含更新信息的博客信息DTO信息</param> /// <returns>业务操作结果</returns> public virtual Task <OperationResult> UpdateBlogs(params BlogInputDto[] dtos) { Check.Validate <BlogInputDto, int>(dtos, nameof(dtos)); return(BlogRepository.UpdateAsync(dtos, async(dto, entity) => { if (await BlogRepository.CheckExistsAsync(m => m.Url == dto.Url, dto.Id)) { throw new OsharpException($"Url为“{dto.Url}”的博客已存在,不能重复"); } })); }
public IActionResult DeletePost(string key, string postid, string username, string password, bool publish) { Post post = BlogRepository.GetAll(Blog.Id).FirstOrDefault(p => p.PostId == postid); if (post != null) { post.BlogId = Blog.Id; BlogRepository.Delete(post); } return(new XmlRpcResult(post != null)); }
public void AddNewPost_ShouldReturnNullException() { //arrange var repo = new BlogRepository(); //act repo.AddNewPost(new Post { Author = "" }); //assert }
public ActionResult Index() { BlogRepository _blogRepository = new BlogRepository(); List <Blog> blogs = new List <Blog>(); if (_blogRepository.GetAll() != null) { blogs = _blogRepository.GetAll(); } return(View(blogs)); }
public void ShouldNotCommitToDatabaseOnDataChange() { //Arrange IDbContext mockContext = MockRepository.GenerateMock<IDbContext>(); IUnitOfWork unitOfWork = new UnitOfWork(mockContext); mockContext.Stub(x => x.Find<Blog>()).Return(new List<Blog>() { new Blog() { Id = 1, Title = "Test" } }.AsQueryable()); IBlogRepository repository = new BlogRepository(unitOfWork); var items = repository.Set<Blog>(); //Act items.First().Title = "Not Going to be Written"; //Assert mockContext.AssertWasNotCalled(x => x.SaveChanges()); }
public ActionResult GuestSearchByTitle(string term) { var repo = new BlogRepository(); IEnumerable <BlogPost> found = repo.SearchByTitle(term); if (!found.Any()) { return(HttpNotFound("Search returned no results.")); } return(Json(found, "application/json", JsonRequestBehavior.AllowGet)); }
public UnitOfWork() { _context = new FBruContext(); Advertisements = new AdvertisementRepository(_context); Blogs = new BlogRepository(_context); Categories = new CategoryRepository(_context); Dishes = new DishRepository(_context); Images = new ImageRepository(_context); Keywords = new KeywordRepository(_context); Restaurants = new RestaurantRepository(_context); Users = new UserRepository(_context); UserGroups = new UserGroupRepository(_context); }
public bool savePost(BlogPost model) { try { BlogRepository _repository = new BlogRepository(); _repository.SavePost(model); return(true); } catch (Exception) { throw; } }
public void Update(UpdateBlogCommand updatedBlogCommand) { var repo = new BlogRepository(); //var updatedBlog = new Blog //{ // Title = updatedBlogCommand.Title, // Article = updatedBlogCommand.Article, // ImageUrl = updatedBlogCommand.ImageUrl, // }; repo.UpdateBlog(updatedBlogCommand); }
public ActionResult DeletePost(int id) { var repo = new BlogRepository(); BlogPost model = repo.BlogPostSelectById(id); if (model == null) { return(RedirectToAction("Index", "Admin")); } return(View(model)); }
public void AddPost_OnePostInDb_ReturnCorrectNumberOfPosts() { var repository = new BlogRepository(); var post = new Post { Author = "aaa", Content = "xyz" }; repository.AddPost(post); var result = repository.GetAllPosts(); Assert.AreEqual(2, result.Count()); }
public virtual async Task <BlogPostPublicDto> GetAsync( [NotNull] string blogSlug, [NotNull] string blogPostSlug) { var blog = await BlogRepository.GetBySlugAsync(blogSlug); var blogPost = await BlogPostRepository.GetBySlugAsync(blog.Id, blogPostSlug); var blogPostDto = ObjectMapper.Map <BlogPost, BlogPostPublicDto>(blogPost); blogPostDto.ContentFragments = await ContentParser.ParseAsync(blogPost.Content); return(blogPostDto); }
public void AddComment_NoContentGiven_ThrowsException() { var context = new BlogContext(); context.Database.CreateIfNotExists(); var repository = new BlogRepository(); var allPosts = repository.GetAllPosts(); var id = allPosts.ElementAt(0).Id; repository.AddNewComment(new Comment { Id = 222, PostId = id }); }
public void after_creating_new_blog_blogs_count_in_db_equals_one() { var testBlogTitle = "test blog title"; var count = new BlogRepository().GetBlogsCount(); Assert.AreEqual(0, count); new BlogRepository().CreateBlog(GetSampleBlog(testBlogTitle)); count = new BlogRepository().GetBlogsCount(); Assert.AreEqual(1, count); }
public async Task <IActionResult> Edit() { var currentUser = await UserRepository.GetUserAsync(User); var author = await BlogRepository.GetAuthorByUserIdAsync(currentUser.Id, CancellationToken.None); if (author == null) { author = CreateFromUser(currentUser); await BlogRepository.CreateOrUpdateAuthorAsync(author, CancellationToken.None); } return(View(author)); }
public IActionResult GetCategories(string blogid, string username, string password) { var categories = BlogRepository.GetCategories(blogid); var list = new List <object>(); foreach (string category in categories.Keys) { list.Add(new { title = category }); } return(new XmlRpcResult(list.ToArray())); }
public virtual async Task <PagedResultDto <BlogPostPublicDto> > GetListAsync([NotNull] string blogSlug, BlogPostGetListInput input) { var blog = await BlogRepository.GetBySlugAsync(blogSlug); var blogPosts = await BlogPostRepository.GetListAsync(null, blog.Id, input.AuthorId, input.TagId, BlogPostStatus.Published, input.MaxResultCount, input.SkipCount, input.Sorting); return(new PagedResultDto <BlogPostPublicDto>( await BlogPostRepository.GetCountAsync(blogId: blog.Id, tagId: input.TagId, statusFilter: BlogPostStatus.Published, authorId: input.AuthorId), ObjectMapper.Map <List <BlogPost>, List <BlogPostPublicDto> >(blogPosts))); }
public IActionResult Index() { var blogViewModel = new BlogViewModel { Blog = Blog, Themes = BlogRepository.GetThemes().Select(t => new SelectListItem { Value = t, Text = t }).ToList() }; // ReSharper disable once Mvc.ViewNotResolved return(View("Index", blogViewModel)); }
public void GetAllPost_OnePostInDb_ReturnOnePost() { // arrange var context = new BlogContext(); context.Database.CreateIfNotExists(); var repository = new BlogRepository(); // act var result = repository.GetAllPosts(); // assert Assert.AreEqual(0, result.Count()); }
public void SetUp() { _dbSetContextHelperMock = new DbSetContextHelperMock(); _data = _dbSetContextHelperMock.ListBlogsQueryable(); _mockSet = new Mock <DbSet <Blog> >(); _appDbContext = new Mock <IAppDbContext>(); _dbSetContextHelperMock.ProvideQuaryableMockDbSet(_mockSet, _data); _appDbContext.Setup(b => b.Blogs).Returns(_mockSet.Object); _blogRepository = new BlogRepository(_appDbContext.Object); }
/// <summary> /// Gets a blog by it's ID. /// </summary> /// <param name="blogId">ID of the blog to get.</param> /// <returns>Returns the blog.</returns> /// <exception cref="BlogNotFoundException">Thrown if there is no blog with the provided ID.</exception> public Blog GetBlog(string blogId) { Blog blog = BlogRepository.GetBlog(blogId); if (blog == null) { throw new BlogNotFoundException(blogId); } else { return(blog); } }
public ViewResult Login(Login d) { if (ModelState.IsValid) { string connString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BlogApp;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; SqlConnection con = new SqlConnection(connString); try { string query = $"Select * from Signup where Email='{d.Email}' and Password='******'"; con.Open(); SqlCommand cmd = new SqlCommand(query, con); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { Gmail.gmail = ""; Gmail.gmail = d.Email; if (Gmail.gmail == "*****@*****.**") { List <Post> post = new List <Post>(); BlogRepository b = new BlogRepository(); post = b.AddPost(); return(View("Admin", post)); } else { List <Post> post = new List <Post>(); BlogRepository b = new BlogRepository(); post = b.AddPost(); return(View("BlogView", post)); } } else { return(View()); } } catch (Exception) { return(View()); } finally { con.Close(); } } else { ModelState.AddModelError(string.Empty, "Please enter correct data!"); return(View()); } }
public void BlogRepository_Update() { using (var context = new BlogsDbContext(_options)) { var id = 1; var blogRepository = new BlogRepository(context); var blog = blogRepository.GetById(1).Result; blog.Title = "Modified"; blog.Active = false; var result = blogRepository.Update(blog).Result; var blogMod = blogRepository.GetById(1).Result; Assert.True(blogMod.Active == false && blogMod.Title == "Modified"); } }
public async Task ShouldHaveEntity() { var blobContainerName = this.TestContext.Properties["blobContainerName"].ToString(); var slug = this.TestContext.Properties["slug"].ToString(); var container = cloudStorageAccountClassic.CreateCloudBlobClient().GetContainerReference(blobContainerName); var keys = new AzureBlobKeys(); keys.Add <BlogEntry>(i => i.Slug); var repository = new BlogRepository(keys, container); Assert.IsTrue(await repository.HasEntityAsync <BlogEntry>(slug), "The expected Blog Entry is not in the Repository."); }
public async Task <IActionResult> EditPost(string id) { if (!(await BlogRepository.IsPostIdValid(id, CancellationToken.None))) { return(NotFound()); } return(View("Compose", new PostViewModel() { IsEdit = true, Post = new BlogPostViewModel() { Id = id } })); }
public void should_be_able_to_add_and_read_blog_from_database() { var blogRepository = new BlogRepository(); var testBlogTitle = "test blog title"; var blogToCreate = GetSampleBlog(testBlogTitle); var blogCreated = blogRepository.CreateBlog(blogToCreate); var blogToTest = blogRepository.GetBlogById(blogCreated.Id); Assert.NotNull(blogToTest); Assert.AreEqual(testBlogTitle, blogToTest.Title); Assert.GreaterOrEqual(blogToTest.Id, 1); }
public void can_get_default_blog() { var blogRepository = new BlogRepository(); var testBlogTitle = "test blog title"; var blogToCreate = GetSampleBlog(testBlogTitle); var blogCreated = blogRepository.CreateBlog(blogToCreate); var blogToTest = blogRepository.GetDefaultBlog(); Assert.NotNull(blogToTest); Assert.AreEqual(blogCreated.Title, blogToTest.Title); Assert.AreEqual(blogCreated.Id, blogToTest.Id); }
public void CreateNewAuthorSuccessfulTest() { using (UnitOfWork uow = new UnitOfWork()) { AuthorRepository ar = new AuthorRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); br.Save(b); Author a = new Author("Pasquale", "Garzillo", Convert.ToDateTime("27/12/1987"), "*****@*****.**", true, "rofox2011", b); ar.Save(a); uow.Commit(); } }
public void WillSaveToDb() { var blog = new Blog(); var post = new Post(); blog.AddPost(post); InitDatabase(typeof(Blog).Assembly); using(var scope = new TransactionScope()) { var repository = new BlogRepository(session); repository.Save(blog); // repository.Save(post); scope.Complete(); } }
public void CreateSuccessfulBlogTest() { using (UnitOfWork uow = new UnitOfWork()) { BlogRepository br = new BlogRepository(uow.Current); //Creo il blog Devevil.Blog.Model.Domain.Entities.Blog b = new Devevil.Blog.Model.Domain.Entities.Blog(".Net Help", "Un blog dedicato allo sviluppo"); //creo una categoria generica Category c = new Category("Nessuna categoria", "Categoria generica"); //Creo un paio di TAG Tag t1 = new Tag("C#"); Tag t2 = new Tag(".NET"); //Creo un autore, afferente al blog "b" Author a = new Author("Pasquale", "Garzillo", Convert.ToDateTime("27/12/1987"), "*****@*****.**",true,"rofox2011",b); //Creo una pagina afferente al blog "b", che ha per autore "a" ed appartiene alla categoria "c" Page p = new Page("Prima pagina del blog", "Descrizione della prima pagina", DateTime.Today, "testo pagina", a, b, c); //Creo un commento per la pagina "p" Comment co = new Comment("Raowyr", "*****@*****.**", "Testo commento", p); //Aggiunto i tag "t1" e "t2" alla pagina p.AddTag(t1); p.AddTag(t2); //Aggiungo il commento "co" alla pagina p.AddComment(co); //Aggiungo la pagina "p" al blog "b" b.AddPageToBlog(p); //Aggiungo l'autore "a" al blog "b" b.AddAuthorToBlog(a); //La categoria "c" è categoria della pagina "p" c.AddCategoryToPage(p); //L'autore "a" è autore della pagina "p" a.AddAuthoringPage(p); //Tag "t1" e "t2" sono tag delle pagina "p" t1.AddTagToPage(p); t2.AddTagToPage(p); br.Save(b); uow.Commit(); Devevil.Blog.Model.Domain.Entities.Blog bb = br.GetById(b.Id); Assert.IsNotNull(bb); } }
public Post UpdatePost(int? id, string title, string body, DateTime date, string tags, string photoPath) { BlogRepository _repo = new BlogRepository(); TagBLL tagBLL = new TagBLL(); Post post = _repo.GetPost(id); post.Title = title; post.Body = body; post.Preview = body.BlogPreviewTruncate(); post.Date = date; post.PhotoPath = photoPath; post.DateEdited = DateTime.Now; string newTitle = UrlTitleWithDashes(title); newTitle = SanitizedUrlTitle(newTitle); post.UrlTitle = newTitle; post.Tags.Clear(); post.Tags = tagBLL.CreateTag(tags); List<string> tagList = post.Tags.Select(x => x.Name).ToList(); if (tagList.Count != 0) { if (post.Views == 0) { int tagSuccess = _repo.IncrementTags(tagList); } } if (post.Views > 0) { //Stupid logic, should have a different method for UpdatePost and NewPost...ugh. post.Views--; } bool success = _repo.SavePost(post); return success ? post : null; }
public void ShouldFilterTestData() { //Arrange IQueryable<Blog> items = new List<Blog> { new Blog() { Creationdate = DateTime.Now, ShortDescription = "Test", Title = "Test" }, new Blog() { Creationdate = DateTime.Now, ShortDescription = "not this one", Title = "Blog" }, new Blog() { Creationdate = DateTime.Now, ShortDescription = "not this", Title = "TeBlog" }, new Blog() { Creationdate = DateTime.Now, ShortDescription = "not this one", Title = "TestBlog" } }.AsQueryable(); var context = MockRepository.GenerateStrictMock<IDbContext>(); context.Expect(x => x.AsQueryable<Blog>()).Return(items.AsQueryable()); var repository = new BlogRepository(context); //Act var spec = new TitleNameQuery("Test"); var returnedValues = repository.Find(spec); //Assert Assert.AreEqual(1, returnedValues.Count()); }
public ActionResult Index(SetupViewModel model) { try { if (ModelState.IsValid) { Model.Domain.Entities.Blog b = new Model.Domain.Entities.Blog(model.Blog, model.Descrizione); Author au = new Author(model.Nome, model.Cognome, model.Nascita, model.Email, true, model.Password, b); Category cc = new Category("Nessuna categoria", "Categoria generica"); using (UnitOfWork uow = new UnitOfWork()) { BlogRepository br = new BlogRepository(uow.Current); AuthorRepository ar = new AuthorRepository(uow.Current); CategoryRepository cr = new CategoryRepository(uow.Current); br.Save(b); ar.Save(au); cr.Save(cc); uow.Commit(); } //Vai alla pagina di gestione return RedirectToAction("Index", "Manage"); } else return View(model); } catch (Exception ex) { return Error(ex); } }
public void ShouldNotCommitOnError() { //Arrange IDbContext mockContext = MockRepository.GenerateMock<IDbContext>(); IUnitOfWork unitOfWork = new UnitOfWork(mockContext); mockContext.Stub(x => x.Find<Blog>()).Return(new List<Blog>() { new Blog() { Id = 1, Title = "Test" } }.AsQueryable()); mockContext.Stub(x => x.SaveChanges()).Throw(new ApplicationException()); IBlogRepository repository = new BlogRepository(unitOfWork); var items = repository.Set<Blog>(); items.First().Title = "Not Going to be Written"; //Act try { repository.SaveChanges(); } catch (Exception) { } //Assert mockContext.AssertWasCalled(x => x.Rollback()); }
public void Automatically_migrate_to_new_Schema() { var repository = new BlogRepository(redisClient); //Populate the datastore with the old schema from the 'BlogPostBestPractice' BlogPostBestPractice.InsertTestData(repository); //Create a typed-client based on the new schema using (var redisBlogPosts = redisClient.GetTypedClient<New.BlogPost>()) { //Automatically retrieve blog posts IList<New.BlogPost> allBlogPosts = redisBlogPosts.GetAll(); //Print out the data in the list of 'New.BlogPost' populated from old 'BlogPost' type //Note: renamed fields are lost Console.WriteLine(allBlogPosts.Dump()); /*Output: [ { Id: 3, BlogId: 2, PostType: None, Title: Redis, Labels: [], Tags: [ Redis, NoSQL, Scalability, Performance ], Comments: [ { Content: First Comment!, CreatedDate: 2010-04-28T21:42:03.9484725Z } ] }, { Id: 4, BlogId: 2, PostType: None, Title: Couch Db, Labels: [], Tags: [ CouchDb, NoSQL, JSON ], Comments: [ { Content: First Comment!, CreatedDate: 2010-04-28T21:42:03.9484725Z } ] }, { Id: 1, BlogId: 1, PostType: None, Title: RavenDB, Labels: [], Tags: [ Raven, NoSQL, JSON, .NET ], Comments: [ { Content: First Comment!, CreatedDate: 2010-04-28T21:42:03.9004697Z }, { Content: Second Comment!, CreatedDate: 2010-04-28T21:42:03.9004697Z } ] }, { Id: 2, BlogId: 1, PostType: None, Title: Cassandra, Labels: [], Tags: [ Cassandra, NoSQL, Scalability, Hashing ], Comments: [ { Content: First Comment!, CreatedDate: 2010-04-28T21:42:03.9004697Z } ] } ] */ } }
public void Manually_migrate_to_new_Schema_using_a_custom_tranlation() { var repository = new BlogRepository(redisClient); //Populate the datastore with the old schema from the 'BlogPostBestPractice' BlogPostBestPractice.InsertTestData(repository); //Create a typed-client based on the new schema using (var redisBlogPosts = redisClient.GetTypedClient<BlogPost>()) using (var redisNewBlogPosts = redisClient.GetTypedClient<New.BlogPost>()) { //Automatically retrieve blog posts IList<BlogPost> oldBlogPosts = redisBlogPosts.GetAll(); //Write a custom translation layer to migrate to the new schema var migratedBlogPosts = oldBlogPosts.ConvertAll(old => new New.BlogPost { Id = old.Id, BlogId = old.BlogId, Title = old.Title, Content = old.Content, Labels = old.Categories, //populate with data from renamed field PostType = New.BlogPostType.Article, //select non-default enum value Tags = new HashSet<string>(old.Tags), Comments = old.Comments.ConvertAll(x => new Dictionary<string, string> { { "Content", x.Content }, { "CreatedDate", x.CreatedDate.ToString() }, }), NoOfComments = old.Comments.Count, //populate using logic from old data }); //Persist the new migrated blogposts redisNewBlogPosts.StoreAll(migratedBlogPosts); //Read out the newly stored blogposts var refreshedNewBlogPosts = redisNewBlogPosts.GetAll(); //Note: data renamed fields are successfully migrated to the new schema Console.WriteLine(refreshedNewBlogPosts.Dump()); /* [ { Id: 3, BlogId: 2, PostType: Article, Title: Redis, Labels: [ NoSQL, Cache ], Tags: [ Redis, NoSQL, Scalability, Performance ], Comments: [ { Content: First Comment!, CreatedDate: 28/04/2010 22:58:35 } ], NoOfComments: 1 }, { Id: 4, BlogId: 2, PostType: Article, Title: Couch Db, Labels: [ NoSQL, DocumentDB ], Tags: [ CouchDb, NoSQL, JSON ], Comments: [ { Content: First Comment!, CreatedDate: 28/04/2010 22:58:35 } ], NoOfComments: 1 }, { Id: 1, BlogId: 1, PostType: Article, Title: RavenDB, Labels: [ NoSQL, DocumentDB ], Tags: [ Raven, NoSQL, JSON, .NET ], Comments: [ { Content: First Comment!, CreatedDate: 28/04/2010 22:58:35 }, { Content: Second Comment!, CreatedDate: 28/04/2010 22:58:35 } ], NoOfComments: 2 }, { Id: 2, BlogId: 1, PostType: Article, Title: Cassandra, Labels: [ NoSQL, Cluster ], Tags: [ Cassandra, NoSQL, Scalability, Hashing ], Comments: [ { Content: First Comment!, CreatedDate: 28/04/2010 22:58:35 } ], NoOfComments: 1 } ] */ } }
protected override void Establish_context() { base.Establish_context(); this._repository = new BlogRepository(base._dbContext); }
public ActionResult PageDetail(int id) { try { PageViewModel pvm = new PageViewModel(); using (UnitOfWork uow = new UnitOfWork()) { PageRepository pr = new PageRepository(uow.Current); AuthorRepository ar = new AuthorRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); CategoryRepository cr = new CategoryRepository(uow.Current); Page p = pr.GetById(id); if (p != null) { IList<Author> tmpAuthors = ar.FindAll().ToList(); if (tmpAuthors != null && tmpAuthors.Count > 0) { IEnumerable<SelectListItem> tmpAuthorsItems; tmpAuthorsItems = from s in tmpAuthors select new SelectListItem { Text = s.NameAndSurname, Value = s.Id.ToString() }; pvm.Authors = tmpAuthorsItems; pvm.SelectedAuthor = p.Author.Id.ToString(); } IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList(); if (tmpBlogs != null && tmpBlogs.Count > 0) { IEnumerable<SelectListItem> tmpBlogsItems; tmpBlogsItems = from b in tmpBlogs select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; pvm.Blogs = tmpBlogsItems; pvm.SelectedBlog = p.Blog.Id.ToString(); } IList<Category> tmpCategories = cr.FindAll().ToList(); if (tmpCategories != null && tmpCategories.Count > 0) { IEnumerable<SelectListItem> tmpCategoriesItems; tmpCategoriesItems = from b in tmpCategories select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; pvm.Categories = tmpCategoriesItems; pvm.SelectedCategory = p.Category.Id.ToString(); } pvm.Data = p.Date.Value; pvm.Id = p.Id; pvm.Titolo = p.Title; pvm.Descrizione = p.Description; pvm.FileName = p.ImageName; pvm.Body = p.BodyText; if (p.Tags != null && p.Tags.Count > 0) pvm.Tags = String.Join(", ", p.Tags.Select(x=>x.Name)); } } return View(pvm); } catch (Exception ex) { return Error(ex); } }
static void Main(string[] args) { var blogs = new BlogRepository(null); Console.WriteLine(blogs.FindById(1).Title); }
public void FindByIdTest() { BlogRepository repo = new BlogRepository(); Blog blog = repo.FindById(1); Assert.AreEqual(blog.Title, "My Blog"); }
public ActionResult PageNew(PageViewModel model) { try { //Carica tutti gli elementi necessari a video using (UnitOfWork uow = new UnitOfWork()) { AuthorRepository ar = new AuthorRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); CategoryRepository cr = new CategoryRepository(uow.Current); //Ricarica la lista autori IList<Author> tmpAuthors = ar.FindAll().ToList(); if (tmpAuthors != null && tmpAuthors.Count > 0) { IEnumerable<SelectListItem> tmpAuthorsItems; tmpAuthorsItems = from s in tmpAuthors select new SelectListItem { Text = s.NameAndSurname, Value = s.Id.ToString() }; model.Authors = tmpAuthorsItems; } IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList(); if (tmpBlogs != null && tmpBlogs.Count > 0) { IEnumerable<SelectListItem> tmpBlogsItems; tmpBlogsItems = from b in tmpBlogs select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; model.Blogs = tmpBlogsItems; } IList<Category> tmpCategories = cr.FindAll().ToList(); if (tmpCategories != null && tmpCategories.Count > 0) { IEnumerable<SelectListItem> tmpCategoriesItems; tmpCategoriesItems = from b in tmpCategories select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; model.Categories = tmpCategoriesItems; } } if (ModelState.IsValid) { using (UnitOfWork uow = new UnitOfWork()) { string fileName = null; if (model.File != null && model.File.ContentLength > 0) { //SALVA IL FILE fileName = Path.GetFileName(model.File.FileName); var path = Path.Combine(Server.MapPath("/Uploads"), fileName); model.File.SaveAs(path); model.FileName = fileName; } model.SelectedAuthor = model.SelectedAuthor; model.SelectedBlog = model.SelectedBlog; model.SelectedCategory = model.SelectedCategory; PageRepository pr = new PageRepository(uow.Current); AuthorRepository ar = new AuthorRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); CategoryRepository cr = new CategoryRepository(uow.Current); TagRepository tr = new TagRepository(uow.Current); Author au = ar.GetById(Convert.ToInt32(model.SelectedAuthor)); Blog.Model.Domain.Entities.Blog bb = br.GetById(Convert.ToInt32(model.SelectedBlog)); Category cc = cr.GetById(Convert.ToInt32(model.SelectedCategory)); Page p = new Page(model.Titolo, model.Descrizione, model.Data, model.Body, au, bb, cc); if (!String.IsNullOrEmpty(model.Tags)) { foreach(var t in model.Tags.Split(',')) { if (!String.IsNullOrEmpty(t)) { Tag tg = tr.GetTagByName(t.TrimStart().TrimEnd()); if (tg != null) { p.AddTag(tg); } else { Tag tempTag = new Tag(t.TrimStart().TrimEnd()); p.AddTag(tempTag); } } } } if (!String.IsNullOrEmpty(fileName)) p.SetImagePath(fileName); else model.FileName = p.ImageName; pr.SaveOrUpdate(p); uow.Commit(); model.Message = "Salvataggio eseguito con successo!"; } } return View(model); } catch (Exception ex) { return Error(ex); } }
public ActionResult PageNew() { try { PageViewModel pvm = new PageViewModel(); using (UnitOfWork uow = new UnitOfWork()) { AuthorRepository ar = new AuthorRepository(uow.Current); BlogRepository br = new BlogRepository(uow.Current); CategoryRepository cr = new CategoryRepository(uow.Current); //Ricarica la lista autori IList<Author> tmpAuthors = ar.FindAll().ToList(); if (tmpAuthors != null && tmpAuthors.Count > 0) { IEnumerable<SelectListItem> tmpAuthorsItems; tmpAuthorsItems = from s in tmpAuthors select new SelectListItem { Text = s.NameAndSurname, Value = s.Id.ToString() }; pvm.Authors = tmpAuthorsItems; } IList<Blog.Model.Domain.Entities.Blog> tmpBlogs = br.FindAll().ToList(); if (tmpBlogs != null && tmpBlogs.Count > 0) { IEnumerable<SelectListItem> tmpBlogsItems; tmpBlogsItems = from b in tmpBlogs select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; pvm.Blogs = tmpBlogsItems; } IList<Category> tmpCategories = cr.FindAll().ToList(); if (tmpCategories != null && tmpCategories.Count > 0) { IEnumerable<SelectListItem> tmpCategoriesItems; tmpCategoriesItems = from b in tmpCategories select new SelectListItem { Text = b.Name, Value = b.Id.ToString() }; pvm.Categories = tmpCategoriesItems; } pvm.Data = DateTime.Today.Date; } return View(pvm); } catch (Exception ex) { return Error(ex); } }
public void ShouldConnectToTheDatabase() { var repository = new BlogRepository(new BlogContext(Settings.Default.BlogConnection)); var results = repository.Find(new TitleNameQuery("Test")); }
public BlogsController() { _repository = new BlogRepository(Settings); }
public PostsController() { _postRpository = new PostRepository() { Settings = Settings }; _blogRepository = new BlogRepository() { Settings = Settings }; }
public void ShouldReadToDatabaseOnRead() { //Arrange IDbContext mockContext = MockRepository.GenerateMock<IDbContext>(); IUnitOfWork unitOfWork = new UnitOfWork(mockContext); IBlogRepository repository = new BlogRepository(unitOfWork); //Act var items = repository.Set<Blog>(); //Assert mockContext.AssertWasCalled(x => x.Find<Blog>()); }
public PostsController() { _postRpository = new PostRepository(Settings); _blogRepository = new BlogRepository(Settings); }
public UnitOfWork(BlogContext context) { _context = context; Blogs = new BlogRepository(_context); Posts = new PostRepository(_context); }