public void Setup() { _transactionScope = new TransactionScope(); _nickname = "nickname"; _post1 = BuildMeA.Post("Title", "Entry", DateTime.Today, DateTime.Today); _blog1 = BuildMeA .Blog("title", "description", _nickname, DateTime.Now) .WithPost(_post1); _user1 = BuildMeA.User("email", "name", "password") .WithBlog(_blog1); _post2 = BuildMeA.Post("Title", "Entry", DateTime.Today, DateTime.Today, false); Blog blog2 = BuildMeA .Blog("title", "description", "nickname2", DateTime.Now) .WithPost(_post2); _user2 = BuildMeA.User("email", "name2", "password") .WithBlog(blog2); _userRepository = new UserRepository(ConfigurationManager.ConnectionStrings["mblog"].ConnectionString); _postRepository = new PostRepository(ConfigurationManager.ConnectionStrings["mblog"].ConnectionString); }
public void GetPost_Test() { PostRepository repository = new PostRepository(BaseTest.ServerMapPathFacked); Post post = repository.Get(Guid.Parse("6db3c056-496d-492e-8282-4c86d34d2e59")); Assert.IsNotNull(post); }
public ICollection<PostModelGetAllPosts> GetAllPosts() { try { var PostRepository = new PostRepository(context); var PostModelGetList = new List<PostModelGetAllPosts>(); foreach (PostDto p in PostRepository.GetAllPosts()) { PostModelGetList.Add( new PostModelGetAllPosts() { Id = p.Id, Title = p.Title, Content = p.Content, CreationDate = p.CreationDate, UserId = p.UserId, UserLogin = p.UserLogin, Tags = p.Tags } ); } return PostModelGetList; } catch { throw new HttpResponseException(HttpStatusCode.Forbidden); } }
public void GivenABlogEntry_WhenThenFileIsCreated_AndTheFileIsNotFound_ThenTheCorrectExceptionIsThrown() { _fileInfo.Setup(f => f.Create()).Throws(new IOException()); var entry = new Post { Title = "title", EntryAddedDate = new DateTime(1990, 1, 1) }; var repository = new PostRepository(Path, _fileInfoFactory.Object, null); Assert.Throws<RepositoryException>(() => repository.Create(entry)); }
private static void GetPost(string title) { var postRepository = new PostRepository(); var post = postRepository.GetPostByTitle(title); if (post != null) { Console.WriteLine("Found post '{0}'", post.Title); if (post.Categories.Count > 0) { Console.WriteLine("Categories"); Console.WriteLine("-----------"); foreach (var category in post.Categories) { Console.WriteLine("- {0}", category.Name); } } if (post.Comments.Count > 0) { Console.WriteLine("Comments"); Console.WriteLine("-----------"); foreach (var comment in post.Comments) { Console.WriteLine("{0} said: {1}", comment.Author, comment.Text); } } } }
private void GetPostService(UnitOfWork uow, out ICategoryService categoryService, out IForumService forumService, out ITopicService topicService, out IPostService postService) { ICategoryRepository cateRepo = new CategoryRepository(uow); IForumRepository forumRepo = new ForumRepository(uow); ITopicRepository topicRepo = new TopicRepository(uow); IPostRepository postRepo = new PostRepository(uow); IForumConfigurationRepository configRepo = new ForumConfigurationRepository(uow); IState request = new DummyRequest(); ILogger logger = new ConsoleLogger(); IUserRepository userRepo = new UserRepository(uow); User user = userRepo.Create(new User { Name = "D. Ummy", ProviderId = "12345678", FullName = "Mr. Doh Ummy", EmailAddress = "[email protected]", Culture = "th-TH", TimeZone = "GMT Standard Time" }); List<IEventSubscriber> subscribers = new List<IEventSubscriber>(); IEventPublisher eventPublisher = new EventPublisher(subscribers, logger, request); IUserProvider userProvider = new DummyUserProvider(user); IPermissionService permService = new PermissionService(); IForumConfigurationService confService = new ForumConfigurationService(configRepo); categoryService = new CategoryService(userProvider, cateRepo, eventPublisher, logger, permService); forumService = new ForumService(userProvider, cateRepo, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService); topicService = new TopicService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService); postService = new PostService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService); }
public ActionResult Create(FormCollection formCollection) { string title = formCollection.Get("Title"); string body = formCollection.Get("Body"); bool isPublic = formCollection.Get("IsPublic").Contains("true"); IRepository<Category> categoriesRepo = new CategoryRepository(); IRepository<Post> postsRepo = new PostRepository(); List<Category> allCategories = (List<Category>)categoriesRepo.GetAll(); Post post = new Post(); post.Body = body; post.Title = title; post.CreationDate = DateTime.Now; post.IsPublic = isPublic; foreach (Category category in allCategories) { if (formCollection.Get(category.Id.ToString()).Contains("true")) post.Categories.Add(category); } postsRepo.Save(post); return RedirectToAction("Index"); }
public ActionResult Details(Guid id) { IRepository<Post> repo = new PostRepository(); Post post = repo.GetById(id); PostViewModel model = new PostViewModel(post); return View(model); }
public AdminController(PostRepository repo, IRepository<Category> category, IRepository<Location> locationRepo, IAccountRepository account) { _postRepo = repo; _categoryRepo = category; _locationRepo = locationRepo; _accountRepo = account; }
public void RemovePost_Test() { Post post1 = CreatePost(); Post post2 = CreatePost(); PostRepository repository = new PostRepository(BaseTest.ServerMapPath); repository.Insert(post1); repository.Insert(post2); repository.Remove(post1.Id); string file = string.Concat(BaseTest.StorageXmlPath, "Post_", post1.Id, ".xml"); Assert.IsFalse(File.Exists(file), "The fille exist: " + file); XDocument documnetRepository = XDocument.Load(BaseTest.StorageXmlPath + "Post.xml"); XElement postInReposioty = documnetRepository.Root .Elements("Post") .Where(p=>p.Attribute("Id").Value == post1.Id.ToString()) .SingleOrDefault(); Assert.IsNull(postInReposioty, "The element Post does not removed"); }
public void Setup() { _fileInfo = new Mock<IFileInfo>(); _fileInfoFactory = new Mock<IFileInfoFactory>(); _directoryInfo = new Mock<IDirectoryInfo>(); _fileInfoFactory.Setup(f => f.CreateFileInfo(It.IsAny<string>())).Returns(_fileInfo.Object); _repository = new PostRepository("path", _fileInfoFactory.Object, _directoryInfo.Object); }
public void Setup() { r = new PostRepository(); pb = new PostBuilder(); MongoSetup(); collection = database.GetCollection<Post>("posts"); collection.Drop(); }
public ActionResult Edit(Guid id) { IRepository<Post> postsRepo = new PostRepository(); IRepository<Category> categoriesRepo = new CategoryRepository(); PostViewModel model = new PostViewModel(postsRepo.GetById(id), categoriesRepo.GetAll()); return View(model); }
public AdminController(PostRepository repo, IRepository<Category> category, IRepository<Image> image, IRepository<Location> locationRepo, IAccountRepository account, IEventRepository eventRepo) { _eventRepo = eventRepo; _postRepo = repo; _postRepo.Model = _eventRepo.Model; _categoryRepo = category; _categoryRepo.Model = _eventRepo.Model; _accountRepo = account; _accountRepo.Model = _eventRepo.Model; _imgRepo = image; _imgRepo.Model = _eventRepo.Model; _locationRepo = locationRepo; _locationRepo.Model = _eventRepo.Model; }
private static void DeletePost(string title) { var postRepository = new PostRepository(); var post = postRepository.GetPostByTitle(title); if (post != null) { postRepository.Delete(post); } }
protected void Application_Start() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); Posts = new PostRepository(new FileSystem(HostingEnvironment.MapPath("~/App_Data/Posts")), new Cache()); }
// // GET: /Posts/ public ActionResult Index() { IRepository<Post> repo = new PostRepository(); IRepository<SecuritiesHist> repoSecuritieshist = new SecuritiesHistRepository(); IRepository<RightExec> repoExec = new RightExecRepository(); //IList<SecuritiesHist> listSecuritiesHist = repoSecuritieshist.GetAll(); IList<RightExec> listRightExec = repoExec.GetAll(); return View(repo.GetAll()); }
public static void Initialize() { UserRepository = new UserRepository(); PostRepository = new PostRepository(); HeaderImageRepository = new HeaderImageRepository(); MessageRepository = new MessageRepository(); CommentRepository = new CommentRepository(); PostVotingRepository = new PostVotingRepository(); CommentVotingRepository = new CommentVotingRepository(); MessageSettingsRepository = new MessageSettingsRepository(); TagRepository = new TagRepository(); TagPostRepository = new TagPostRepository(); }
public void ShouldCreateAndRetrievePost() { var repository = new PostRepository(connection, transaction); var post = new Post{ Title = "test", Content = "empty", Uri = "archive/2009/01/01/hello" }; repository.InsertPost(post); var retrievedPost = repository.GetPostByUri(post.Uri); Assert.AreEqual(retrievedPost.Title, post.Title); Assert.AreEqual(retrievedPost.Content, post.Content); Assert.AreEqual(retrievedPost.Uri, post.Uri); }
public HttpResponseMessage Delete(int postId) { try { var PostRepository = new PostRepository(context); PostRepository.DeletePost(postId); return Request.CreateResponse(HttpStatusCode.OK, "Post excluído com sucesso."); } catch (Exception e) { return Request.CreateResponse(HttpStatusCode.Forbidden, "Erro " + e.Message); } }
public void GivenABlogEntry_WhenTheEntryIsWrittenToAFile_ThenTheCorrectJsonIsWritten() { var stream = new MemoryStream(); _fileInfo.Setup(f => f.Create()).Returns(stream); var entry = new Post { Title = "title", EntryAddedDate = new DateTime(1990, 1, 1), EntryUpdateDate = new DateTime(1991, 2, 2), Body = "post" }; var repository = new PostRepository(Path, _fileInfoFactory.Object, null); repository.Create(entry); var data = stream.ToArray(); var json = Encoding.UTF8.GetString(data); var savedentry = JsonSerializer.Deserialize<Post>(json); savedentry.Title.Should().Be("title"); savedentry.Body.Should().Be("post"); savedentry.EntryAddedDate.Should().Be(new DateTime(1990, 1, 1)); savedentry.EntryUpdateDate.Should().Be(new DateTime(1991, 2, 2)); }
public void DataPost_Test() { PostRepository repository = new PostRepository(BaseTest.ServerMapPathFacked); var result = repository.Data.ToList(); Assert.IsTrue(result.Count > 0, "There are no files xml"); Assert.IsFalse(result[0].Tags == null, "Tags is null"); Assert.IsTrue(result[0].Tags.Count() == 3, "There are no tags"); Assert.IsFalse(result[0].Comments == null, "Comments is null"); Assert.IsTrue(result[0].Comments.Count() > 0, "There are no comments"); }
public void Delete_Existing_RecordDeleted() { Post post = new Post() { ID = Guid.NewGuid(), PostData = "Data", PostDate = DateTime.Now, RelationID = this.TestPost2.RelationID }; PostRepository Repository = new PostRepository(helper); Repository.Insert(post); Repository.Delete(post); Assert.AreEqual(null, Repository.GetByID(post.ID)); }
public void load_posts() { //// Arrange var filesystem = Substitute.For<FileSystem>(string.Empty); filesystem.GetFiles(Arg.Any<string>()) .Returns(info => new[] {GetFileMock(), GetFileMock(), GetFileMock()}); var repository = new PostRepository(filesystem); //// Act var posts = repository; //// Assert posts.Should().HaveCount(3); }
public void load_single_post_by_name() { //// Arrange var filesystem = Substitute.For<FileSystem>(string.Empty); filesystem.GetFiles(Arg.Any<string>()) .Returns(info => new[] {GetFileMock()}); var repository = new PostRepository(filesystem); //// Act var post = repository.FindByName("this-is-a-test"); //// Assert post.Should().NotBeNull(); post.Name.Should().Be("this-is-a-test"); }
public UnitOfWork( ApplicationDbContext context, UserManager <User> userManager, SignInManager <User> signInManager, IPasswordHasher <User> passwordHasher ) { _context = context; CertificateRepository = new CertificateRepository(_context); ContactRepository = new ContactRepository(_context); PostCategoryRepository = new PostCategoryRepository(_context); PostCommentRepository = new PostCommentRepository(_context); PostRepository = new PostRepository(_context); ProgressBarRepository = new ProgressBarRepository(_context); SettingRepository = new SettingRepository(_context); UserRepository = new UserRepository(userManager, signInManager, passwordHasher); }
private static void CreatePost(string title, string content, string slug, string datePublished, int authorId, IEnumerable <int> tags) { var result = PostRepository.Get(slug); DateTime?published = null; if (result != null) { throw new HttpException(409, "Slug is already in use."); } if (!string.IsNullOrWhiteSpace(datePublished)) { published = DateTime.Parse(datePublished); } PostRepository.Add(title, content, slug, published, authorId, tags); }
public void Initialize() { db = new BlogContext(); postRepository = new PostRepository(db); mockUOW = new Mock <UnitOfWork>(db, postRepository); post = new Post { Id = 100, Title = "Amazon", Description = "Amazon daily deals for Tuesday, April 17", Category = "Technology", Content = "If you\'re looking to add a little extra security for your house, Amazon has plenty of deals on surveillance cameras so you can keep an eye on things.\r\nDIYers can also pick up a DeWALT drill and impact combo kit for their next project, and outdoor enthusiasts can save up to 25% on boating and fishing gear. \r\n\r\nThere are also lightning deals on summer wear like tank tops and water shoes, not to mention smartphone charging accessories like an Anker power bank and a Qi-enabled wireless charger.\r\n", Author = "*****@*****.**", }; mockUOW.Object.Post.Create(post); mockUOW.Object.Save(); }
public async Task<ActionResult> Photo() { var photo = Request.Files["filePhoto"]; var id = Request["Id"]; var dir = Server.MapPath("~/Upload/" + User.Identity.Name); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } var filename = Guid.NewGuid() + Path.GetExtension(photo.FileName); var fullPath = Path.Combine(dir, filename); photo.SaveAs(fullPath); var postRepo = new PostRepository(); await postRepo.UpdatePhoto(id, fullPath); return Json(new { success = true, responseText = "Added." }, JsonRequestBehavior.AllowGet); }
/// <summary> /// Configures the api. /// </summary> /// <param name="modelCache">The optional model cache</param> /// <param name="imageProcessor">The optional image processor</param> private void Setup(IContentServiceFactory factory, ICache modelCache = null, IImageProcessor imageProcessor = null) { cache = modelCache; var cacheLevel = (int)App.CacheLevel; Aliases = new AliasRepository(this, db, cacheLevel > 2 ? cache : null); Archives = new ArchiveRepository(this, db); Categories = new CategoryRepository(this, db, cacheLevel > 2 ? cache : null); Media = new MediaRepository(this, db, storage, cacheLevel > 2 ? cache : null, imageProcessor); Pages = new PageRepository(this, db, factory, cacheLevel > 2 ? cache : null); PageTypes = new PageTypeRepository(db, cacheLevel > 1 ? cache : null); Params = new ParamRepository(db, cacheLevel > 0 ? cache : null); Posts = new PostRepository(this, db, factory, cacheLevel > 2 ? cache : null); PostTypes = new PostTypeRepository(db, cacheLevel > 1 ? cache : null); Sites = new SiteRepository(this, db, cacheLevel > 0 ? cache : null); Tags = new TagRepository(db, cacheLevel > 2 ? cache : null); }
public void Create_Inserts_New_Post() { // Arrange var repository = new PostRepository(new BlogAppSqlServerContext(DbConnectionString), _mapper); var postToCreate = new PostDto() { BlogId = 1, Title = "Some fake title", Content = "Some fake content" }; // Act repository.Create(postToCreate); // Assert Assert.True(postToCreate.Id > 0); }
private static void LerPagina(PaginaFBO pagina, int lastPage) { var postRepository = new PostRepository(); for (int i = 1; i <= lastPage; i++) { List <Post> posts = new List <Post>(); pagina.MudarPagina(i); for (int j = 0; j < 100; j++) { var post = pagina.GetPost(j); posts.Add(post); } postRepository.AddRange(posts); } }
public void AddPageData(string pageName, PageData pageData) { if (PostRepository.Count(e => e.Name == pageData.Name && e.Page.Name == pageName) > 0) { throw new UserFriendlyException("文章名称已重复"); } var page = PageRepository.GetAll().OfType <ContentPage>().FirstOrDefault(e => e.Name == pageName); if (page == null) { throw new UserFriendlyException("找不到要添加的文章页面"); } pageData.Page = page; PostRepository.Insert(pageData); }
public DataParserWorkwearItems( NomenclatureRepository nomenclatureRepository, PostRepository postRepository, NormRepository normRepository, SizeService sizeService) { AddColumnName(DataTypeWorkwearItems.PersonnelNumber, "Табельный номер" ); AddColumnName(DataTypeWorkwearItems.ProtectionTools, "Номенклатура нормы" ); AddColumnName(DataTypeWorkwearItems.Nomenclature, "Номенклатура" ); AddColumnName(DataTypeWorkwearItems.Subdivision, "Подразделение" ); AddColumnName(DataTypeWorkwearItems.Post, "Должность" ); AddColumnName(DataTypeWorkwearItems.Size, "Размер", "Значение антропометрии" //ОСМиБТ ); AddColumnName(DataTypeWorkwearItems.Growth, "Рост" ); AddColumnName(DataTypeWorkwearItems.SizeAndGrowth, "Характеристика" ); AddColumnName(DataTypeWorkwearItems.IssueDate, "Дата выдачи" ); AddColumnName(DataTypeWorkwearItems.Count, "Количество", "Кол-во" ); this.nomenclatureRepository = nomenclatureRepository ?? throw new ArgumentNullException(nameof(nomenclatureRepository)); this.postRepository = postRepository ?? throw new ArgumentNullException(nameof(postRepository)); this.normRepository = normRepository ?? throw new ArgumentNullException(nameof(normRepository)); this.sizeService = sizeService ?? throw new ArgumentNullException(nameof(sizeService)); }
private void MainWindow1_Loaded(object sender, RoutedEventArgs e) { StreamReader connectionConfigureFile = new StreamReader("connectionString.txt"); string connectionString = connectionConfigureFile.ReadLine(); dataManage = new TsqlDataManage(connectionString); statusRepository = new StatusRepository(connectionString); departamentRepository = new DepartamentRepository(connectionString); postRepository = new PostRepository(connectionString); statusBox.Items.Add(new Status() { Id = -1, Name = "*" }); foreach (var status in statusRepository.GetAllEntitys()) { statusBox.Items.Add(status); } statusBox.SelectedIndex = 0; statusBox2.ItemsSource = statusRepository.GetAllEntitys(); statusBox2.SelectedIndex = 0; departmentBox.Items.Add(new Departament() { Id = -1, Name = "*" }); foreach (var departament in departamentRepository.GetAllEntitys()) { departmentBox.Items.Add(departament); } departmentBox.SelectedIndex = 0; postBox.Items.Add(new Post() { Id = -1, Name = "*" }); foreach (var post in postRepository.GetAllEntitys()) { postBox.Items.Add(post); } postBox.SelectedIndex = 0; }
public void SavePostUpdatePost() { PostRepository repo = new PostRepository(fixture.Context, new Site() { ID = Guid.Empty }, null); Post newPost = new Post() { ID = new Guid("0E1684CA-C627-4E87-9F21-843B074D9E4B"), Area = new Area() { Name = "Blog" }, Body = "Body", BodyShort = "BodyShort", Creator = new User() { Name = "Admin" }, Slug = "Slug", State = EntityState.Normal, Tags = new[] { new Tag() { Name = "Test" } }, Title = "Title", }; repo.Save(newPost); Post savedPost = repo.GetPost("Blog", "Slug"); Assert.NotNull(savedPost); Assert.Equal("Blog", savedPost.Area.Name); Assert.Equal("Body", savedPost.Body); Assert.Equal("BodyShort", savedPost.BodyShort); Assert.Equal("Admin", savedPost.Creator.Name); Assert.Equal("Slug", savedPost.Slug); Assert.Equal(EntityState.Normal, savedPost.State); Assert.Equal(1, savedPost.Tags.Count); Assert.True(savedPost.Tags.Select(t => t.Name).Contains("Test")); Assert.Equal("Title", savedPost.Title); }
public void SaveCommentNewAuthedComment() { PostRepository repo = new PostRepository(fixture.Context, new Site() { ID = Guid.Empty }, null); Post existingPost = repo.GetPost(new Area() { Name = "Blog" }, "Hello-World"); Comment newComment = new Comment() { Body = "Body", Creator = new User() { Name = "Admin" }, CreatorIP = 1L, CreatorUserAgent = "UA", Language = new Language() { Name = "en" }, State = EntityState.Normal }; repo.SaveComment(existingPost, newComment); Post editedPost = repo.GetPost(new Area() { Name = "Blog" }, "Hello-World"); Comment addedComment = editedPost.Comments.Where(c => c.Body == "Body").FirstOrDefault(); Assert.NotNull(addedComment); Assert.Equal("Oxite Administrator", addedComment.Creator.Name); Assert.Equal(1L, addedComment.CreatorIP); Assert.Equal("UA", addedComment.CreatorUserAgent); Assert.Equal("en", addedComment.Language.Name); Assert.Equal(EntityState.Normal, addedComment.State); }
/// <summary> /// Gets the post archive according to the given parameters. /// </summary> /// <param name="page">Optional page number</param> /// <param name="year">Optional year</param> /// <param name="month">Optional month</param> /// <returns>The archive</returns> public async Task<Models.Archive> GetArchiveAsync(int page = 1, int? year = null, int? month = null) { var model = new Models.Archive() { Year = year, Month = month }; var rep = new PostRepository(uow); DateTime? start = null; DateTime? stop = null; // Get start and stop dates if (year.HasValue) { start = new DateTime(year.Value, 1, 1); stop = start.Value.AddYears(1); if (month.HasValue) { start = new DateTime(year.Value, month.Value, 1); stop = start.Value.AddMonths(1); } model.TotalCount = await uow.Posts.Where(p => p.Published.HasValue && p.Published >= start && p.Published < stop).CountAsync(); } else { model.TotalCount = await uow.Posts.Where(p => p.Published.HasValue).CountAsync(); } // Calculate paging information model.PageSize = Config.Blog.ArchivePageSize; model.PageCount = Math.Max(Convert.ToInt32(Math.Ceiling(((double)model.TotalCount) / model.PageSize)), 1); model.CurrentPage = Math.Min(page, model.PageCount); // Get the posts if (start.HasValue) { model.Posts = await rep.GetAsync(p => p.Published.HasValue && p.Published >= start && p.Published < stop, model.CurrentPage * model.PageSize); } else { model.Posts = await rep.GetAsync(p => p.Published.HasValue, model.CurrentPage * model.PageSize); } // Filter out the current page model.Posts = model.Posts.Subset((model.CurrentPage - 1) * model.PageSize).ToList(); return model; }
public JsonResult SendPost(string PostText, string Sender, string Room, string dateTime) { //done baby --backenda --TODO: Save postVM to db and send it back to me plz i need it! UserRepository userRepo = new UserRepository(); User sender = userRepo.GetByUsername(Sender); Post post = new Post { PostText = PostText, DateTime = DateTime.Now, Room = Room, Sender = sender.Email, Deleted = false }; PostRepository postRepo = new PostRepository(); postRepo.Add(post); return(Json(post, JsonRequestBehavior.AllowGet)); }
public async void CreatePostTest() { PostRepository postRepository = new PostRepository(_dataContext); Post post = new Post() { AuthorId = 9, Content = "Teste", Date = DateTime.Now, Theme = "Teste", Title = "Teste", }; postRepository.Add(post); await postRepository.SaveChangesAsync(); var result = await postRepository.GetPostByTitleAsync("Teste"); Assert.NotNull(result); }
public void SaveCommentNewAnonComment() { PostRepository repo = new PostRepository(fixture.Context, new Site() { ID = Guid.Empty }, null); CommentRepository repo2 = new CommentRepository(fixture.Context, new Site() { ID = Guid.Empty }, null); Post existingPost = repo.GetPost("Blog", "Hello-World"); Comment newComment = new Comment() { Body = "Body", Creator = new UserBase() { Email = "*****@*****.**", HashedEmail = "XXXXXX", Name = "Test", Url = "http://microsoft.com" }, CreatorIP = 1L, CreatorUserAgent = "UA", Language = new Language() { Name = "en" }, State = EntityState.Normal }; repo2.SaveComment(existingPost, newComment); Comment addedComment = repo2.GetComments(existingPost, false).Where(c => c.Body == "Body").FirstOrDefault(); Assert.NotNull(addedComment); Assert.Equal("*****@*****.**", addedComment.Creator.Email); Assert.Equal("XXXXXX", addedComment.Creator.HashedEmail); Assert.Equal("Test", addedComment.Creator.Name); Assert.Equal("http://microsoft.com", addedComment.Creator.Url); Assert.Equal(1L, addedComment.CreatorIP); Assert.Equal("UA", addedComment.CreatorUserAgent); Assert.Equal("en", addedComment.Language.Name); Assert.Equal(EntityState.Normal, addedComment.State); }
public async Task <PostWithDetailsDto> GetForReadingAsync(GetPostInput input) { var post = await PostRepository.GetPostByUrl(input.BlogId, input.Url); post.IncreaseReadCount(); var postDto = ObjectMapper.Map <Post, PostWithDetailsDto>(post); postDto.Tags = await GetTagsOfPostAsync(postDto.Id); if (postDto.CreatorId.HasValue) { var creatorUser = await UserLookupService.FindByIdAsync(postDto.CreatorId.Value); postDto.Writer = ObjectMapper.Map <BlogUser, BlogUserDto>(creatorUser); } return(postDto); }
static void DeletePost(Thread thread) { var postsByUser = GetPostByCurrentUser(thread); bool isEmpty = !postsByUser.Any(); if (!isEmpty) { int index = 1; foreach (var post in postsByUser) { Console.WriteLine($"Post number:{index}"); Console.WriteLine($"Created by: {post.createdBy}"); Console.WriteLine(post.post_text); Console.WriteLine("---------------------------------"); index++; } var tmpPost = new Post(); Console.WriteLine("These are your posts in this thread. Write the number of the post you want to delete."); bool isOkay = int.TryParse(Console.ReadLine(), out int input); while (!isOkay || !Helper.VerifyIntBetween(1, postsByUser.Count, input)) { Console.WriteLine("You can only enter numbers that exists infront of threads. Try again."); Console.WriteLine("Write the post number of the post you want to delete:"); isOkay = int.TryParse(Console.ReadLine(), out input); } index = 1; foreach (var post in postsByUser) { if (index == input) { tmpPost = post; } index++; } PostRepository.DeletePost(tmpPost); Console.WriteLine("Post deleted."); } else { Console.WriteLine("You don't have any posts in this thread."); } Helper.PressAnyKeyToContinue(); }
public void AddPostTest() { //arrange var userModel = new UserModel() { Name = "Pepa Hnátek", LastLogged = DateTime.Today, MailAddress = "*****@*****.**" }; var userRepository = new UserRepository(dbContextFactory, mapper); userModel = userRepository.Add(userModel); var teamModel = new TeamModel { Description = "Tym resici ics", Name = "Borci" }; var teamRepository = new TeamRepository(dbContextFactory, mapper); teamModel = teamRepository.Add(teamModel); teamRepository.AddUserToTeam(teamModel.Id, userModel.Id); var postModel = new PostModel { Title = "Hlava", Author = userModel, Text = "Ztratil jsem hlavu!", TimeCreated = DateTime.Now, Team = teamModel }; //act var postRepository = new PostRepository(dbContextFactory, mapper); postModel = postRepository.Add(postModel); //assert Assert.Equal("Hlava", postRepository.getById(postModel.Id).Title); teamRepository.Remove(teamModel.Id); //should remove also the post userRepository.Remove(userModel.Id); Assert.Null(postRepository.getById(postModel.Id)); }
public IActionResult AtHome(int id) //return the home view with the id of current loged in user with validations of address. { if (!HttpContext.Session.Keys.Contains("CurrentUser")) { return(RedirectToAction("Login", "Registration")); } List <RegularUser> userData = UserRepository.ReturnUsers(); List <Post> postData = PostRepository.ReturnPosts(); AdminController.manageProfilePic(ref postData); //in order ot manage pics or add default pic in case of no pic if (id == 0) { RegularUser regUsr = userData.Find(regUsr => regUsr.Username == HttpContext.Session.GetString("CurrentUser")); id = regUsr.Id; } ViewBag.Id = id; //to send id of current user to view as well to manage navbar there. postData.Reverse(); return(View("AtHome", postData)); }
internal static void CreateRawItems(Settings settings, PostRepository postRepository) { var workingPath = Path.GetFullPath(WorkingFolderName); Directory.CreateDirectory(workingPath); Page template; using (var stream = AssemblyExtensions.OpenScopedResourceStream <Program> ("Template.xaml")) { template = (Page)XamlReader.Load(stream); template.Width = settings.ItemImageSize.Width; template.Height = settings.ItemImageSize.Height; } var imageFormat = settings.PostImageEncoding; var imageExtension = imageFormat.ToString().ToLower(); var posts = postRepository.RetrievePosts(); foreach (var post in posts) { var relativeBinnedXmlPath = post.ComputeBinnedPath(".xml", settings.FileNameIdFormat); var absoluteBinnedXmlPath = Path.Combine(workingPath, relativeBinnedXmlPath); Directory.CreateDirectory(Path.GetDirectoryName(absoluteBinnedXmlPath)); var element = PivotizePost(post); using (var outputStream = new FileStream(absoluteBinnedXmlPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { using (var writer = new ItemWriter(outputStream, ItemWriterSettings)) { element.Save(writer); } } var relativeBinnedImagePath = post.ComputeBinnedPath(imageExtension, settings.FileNameIdFormat); var absoluteBinnedImagePath = Path.Combine(workingPath, relativeBinnedImagePath); Directory.CreateDirectory(Path.GetDirectoryName(absoluteBinnedImagePath)); using (var outputStream = new FileStream(absoluteBinnedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { ImagePost(post, template, imageFormat, outputStream); } } }
public EmployeeFormPresenter(IMessageService messageService, EmployeeRepository employeeRepository, Employee currentEmployee = null) { _messageService = messageService; _currentEmployee = currentEmployee; _isNewRecord = currentEmployee == null; var postRepository = new PostRepository(); _employeeRepository = employeeRepository; View = new EmployeeForm() { PostList = postRepository.GetAll() }; View.OnFormShow += View_OnFormShow; View.OnApplyChanges += View_OnApplyChanges; View.OnChoosePhoto += View_OnChoosePhoto; View.OnFormClose += View_OnFormClose; }
public static async void Run([QueueTrigger("process-delete-post", Connection = "QUEUESTORAGE_CONNECTION")] CloudQueueMessage myQueueItem, TraceWriter log) { string[] queueItemList = myQueueItem.AsString.Split('.'); string trackId = queueItemList[0]; string postId = queueItemList[1]; var post = await PostRepository.GetPost(trackId, postId); PostRepository.DeletePostFromTableStorage(post); PostRepository.DeletePostFromCosmos(postId); if (post.has_image) { PostRepository.DeleteImages(postId); } // TODO: delete from feeds log.Info($"Deleted post: {post.RowKey}"); }
public ActionResult Feed() { if (!AuthorizeUser()) { return(RedirectToAction("Login", "Accounts")); } var user_id = int.Parse(Session["user_id"].ToString()); PostRepository postRepository = new PostRepository(); var posts = postRepository.GetAllPostByTopicFollow(user_id); foreach (var post in posts) { post.PostContent = WithMaxLength(post.PostContent, 500); } return(View(posts)); }
private static void EditPost(int id, string title, string content, string slug, string datePublished, int authorId, IEnumerable <int> tags) { var result = PostRepository.Get(id); DateTime?published = null; if (result == null) { throw new HttpException(404, "Post does not exist."); } if (!string.IsNullOrWhiteSpace(datePublished)) { published = DateTime.Parse(datePublished); } //PostRepository.Add(title, content, slug, published, authorId); PostRepository.Edit(id, title, content, slug, published, authorId, tags); }
public int DeletePost(string userId, int id) { var user = UserRepository.Find(u => u.Id == userId && u.Status == EntityStatus.Active); if (user != null) { var post = PostRepository.Find(p => p.Id == id && p.Status == EntityStatus.Active); if (post != null) { post.Status = EntityStatus.Deleted; post.SendingStatus = PostStatus.Suspended; PostRepository.Update(post); return(post.Id); } throw new Exception("Post is not found"); } throw new Exception("Not enogh permission"); }
public async Task <IActionResult> List() { _postRepository = new PostRepository(_context); var post = _postRepository.Posts(); List <List <TemplateViewModel> > models = new List <List <TemplateViewModel> >(); foreach (var t in post) { List <TemplateViewModel> tmp = new List <TemplateViewModel>(); foreach (var m in t.Templates) { tmp.Add(JsonConvert.DeserializeObject <TemplateViewModel>(m.Json)); } models.Add(tmp); } Tuple <List <Post>, List <List <TemplateViewModel> > > model = new Tuple <List <Post>, List <List <TemplateViewModel> > >(post, models); return(View("List", model)); }
public async Task <ListResultDto <PostWithDetailsDto> > GetListByBlogIdAndTagNameAsync(Guid id, string tagName) { var posts = await PostRepository.GetPostsByBlogId(id); var tag = tagName.IsNullOrWhiteSpace() ? null : await TagRepository.FindByNameAsync(id, tagName); var userDictionary = new Dictionary <Guid, BlogUserDto>(); var postDtos = new List <PostWithDetailsDto>(ObjectMapper.Map <List <Post>, List <PostWithDetailsDto> >(posts)); foreach (var postDto in postDtos) { postDto.Tags = await GetTagsOfPostAsync(postDto.Id); } if (tag != null) { postDtos = await FilterPostsByTagAsync(postDtos, tag); } foreach (var postDto in postDtos) { if (postDto.CreatorId.HasValue) { if (!userDictionary.ContainsKey(postDto.CreatorId.Value)) { var creatorUser = await UserLookupService.FindByIdAsync(postDto.CreatorId.Value); if (creatorUser != null) { userDictionary[creatorUser.Id] = ObjectMapper.Map <BlogUser, BlogUserDto>(creatorUser); } } if (userDictionary.ContainsKey(postDto.CreatorId.Value)) { postDto.Writer = userDictionary[(Guid)postDto.CreatorId]; } } } return(new ListResultDto <PostWithDetailsDto>(postDtos)); }
// GET: API public JsonResult Posts() { DataContext db = new DataContext(); List <PostDto> postDtos = new List <PostDto>(); IEnumerable <Post> dbPosts = new PostRepository(db).GetPublicPosts(); foreach (Post post in dbPosts) { PostDto postDto = new PostDto() { Content = post.Content, Description = post.Description, Id = post.Id, Title = post.Title }; postDtos.Add(postDto); } return(Json(postDtos, JsonRequestBehavior.AllowGet)); }
public string Excluir(long id) { try { var postRepository = new PostRepository(bd); var post = postRepository.Obter(id); if (post == null) { throw new System.Data.ObjectNotFoundException("Post inexistente!"); } postRepository.Excluir(post); postRepository.Persistir(); return("Post excluído com sucesso."); } catch (Exception ex) { throw ex; } }
public ActionResult EditProfile(Profile Post) { try { if (ModelState.IsValid) { PostRepository PostRepo = new PostRepository(); if (PostRepo.EditProfile(Post)) { ViewBag.Message = "Added successfully"; } } return(View()); } catch { return(View()); } }
private static void GetUserPostsWithComments(int userId) { var postRepository = new PostRepository(); var commentRepository = new CommentRepository(); var posts = postRepository.GetByUserIdAsync(userId); foreach (var post in posts) { var comments = commentRepository.GetByPostId(post.Id); System.Console.WriteLine("-------------------Post--------------------"); System.Console.WriteLine($"{post.Title} - {post.Body}"); System.Console.WriteLine("-------------------Comments--------------------"); foreach (var comment in comments) { System.Console.WriteLine("-------------------Comment--------------------"); System.Console.WriteLine($"{comment.Name}: {comment.Body}"); System.Console.WriteLine("-------------------Comment--------------------"); } } }
private static void CreatePost(string title) { var postRepository = new PostRepository(); var categoryRepository = new CategoryRepository(); var commentRepository = new CommentRepository(); var post = new Post { Title = title, PostedDate = DateTime.Now, Contents = "This is just a simple test post..." }; for (int i = 0; i < 10; i++) { var category = new Category { Name = "Category " + i, CreatedDate = DateTime.Now, Description = "Just a test..." }; post.AddCategory(category); categoryRepository.Create(category); } for (int i = 0; i < 20; i++) { var comment = new Comment { PostedDate = DateTime.Now, Author = "Author " + i, Text = "testing..." }; post.AddComment(comment); commentRepository.Create(comment); } postRepository.Create(post); }
public void load_posts_by_tag() { //// Arrange var filesystem = Substitute.For<FileSystem>(string.Empty); filesystem.GetFiles(Arg.Any<string>()) .Returns(info => new[] {GetFileMock("Code, sitecore"), GetFileMock("Sitecore, Test"), GetFileMock("Test, Code")}); var repository = new PostRepository(filesystem); //// Act var posts = repository.FindByTag("sitecore").ToList(); //// Assert posts.Should().HaveCount(2); foreach (var post in posts) { post.Tags.Count.Should().Be(2); post.Tags.Should().Contain(new Tag("Sitecore")); } }
public void InsertPost_Test() { PostRepository repository = new PostRepository(BaseTest.ServerMapPath); Post post = CreatePost(); repository.Insert(post); string filePathPostRepository = string.Concat(BaseTest.StorageXmlPath, "Post.xml"); string filePathPostOne = string.Concat(BaseTest.StorageXmlPath, string.Format("Post_{0}.xml", post.Id)); Assert.IsTrue(System.IO.File.Exists(filePathPostRepository), "The file not created"); Assert.IsTrue(System.IO.File.Exists(filePathPostOne), "The file not created"); XDocument xDocument = XDocument.Load(filePathPostOne); Assert.IsTrue(xDocument.Root.HasElements, "There is no node Post"); Assert.IsTrue(xDocument.Root.Element("Post").Element("Tags") != null, "There is no node Tags"); Assert.IsTrue(xDocument.Root.Element("Post").Element("Comments") != null, "There is no node Categories"); }