public AnswerStatus CreateBlog(BlogDto blogDTO) { try { using (var uow = _unitOfWorkFactory.Create()) { var blogRepository = _repositoryFactory.CreateBlogRepository(uow); var result = CreateBlog(blogDTO, blogRepository); if (result == AnswerStatus.Failed) { return(result); } uow.SaveChanges(); return(result); } } catch (Exception exc) { _logger.Log(exc.ToString()); return(AnswerStatus.Failed); } }
public AnswerStatus CreateBlog(BlogDto blogDTO, IBlogRepository blogRepository) { try { var newBlog = _blogBuilder.CreateBlog(blogDTO.BlogTitle, DateTime.Now); var userRepository = _repositoryFactory.CreateUserRepository(blogRepository.UnitOfWork); var userCreatedBy = userRepository.GetEntityById(blogDTO.CreatedBy.Id); _userBuilder.SetBlogUserId(userCreatedBy, blogDTO.CreatedBy.Id); _blogBuilder.SetBlogUser(newBlog, userCreatedBy); blogRepository.CreateEntity(newBlog); blogDTO.Id = newBlog.Id; blogDTO.CreationDate = newBlog.CreationDate; if (blogDTO.BlogCategories != null) { var result = CreateCategories(blogDTO, blogRepository.UnitOfWork); if (result == AnswerStatus.Failed) { return(result); } } return(AnswerStatus.Successfull); } catch (Exception exc) { _logger.Log(exc.ToString()); return(AnswerStatus.Failed); } }
public AnswerStatus DeleteBlog(BlogDto blogDTO, IBlogRepository blogRepository) { try { if (blogDTO.Id <= 0) { throw new ArgumentException("id can't be less or equal to 0"); } var blogToDelete = blogRepository.GetEntityById(blogDTO.Id); var deletePostsResult = DeletePosts(blogDTO.Id, blogRepository.UnitOfWork); if (deletePostsResult == AnswerStatus.Failed) { return(deletePostsResult); } var deleteCategoriesResult = DeleteCategories(blogDTO.Id, blogRepository.UnitOfWork); if (deleteCategoriesResult == AnswerStatus.Failed) { return(deleteCategoriesResult); } blogRepository.DeleteEntity(blogToDelete); return(AnswerStatus.Successfull); } catch (Exception exc) { _logger.Log(exc.ToString()); return(AnswerStatus.Failed); } }
public ServiceAnswer <BlogDto> GetBlogByUserId(int userId) { try { using (var uow = _unitOfWorkFactory.Create()) { var blogRepository = _repositoryFactory.CreateBlogRepository(uow); var receivedBlog = blogRepository.GetBlogByUserId(userId); var blogDTO = new BlogDto(); if (receivedBlog != null) { blogDTO = MapReceivedBlog(receivedBlog); } return(new ServiceAnswer <BlogDto>(blogDTO, AnswerStatus.Successfull)); } } catch (Exception exc) { _logger.Log(exc.ToString()); return(new ServiceAnswer <BlogDto>(null, AnswerStatus.Failed)); } }
public IActionResult CreateBlog(BlogCommand blog) { try { if (blog != null) { BlogDto data = _mapper.Map <BlogDto>(blog); var iSuccess = _blogService.AddBlog(data); if (iSuccess) { SuccessModel.SuccessMessage = "Success"; SuccessModel.SuccessCode = "200"; return(Ok(SuccessModel)); } else { ErrorModel.ErrorMessage = "Update fail"; ErrorModel.ErrorCode = "400"; return(StatusCode(400, ErrorModel)); } } else { ErrorModel.ErrorMessage = "Data fail"; ErrorModel.ErrorCode = "400"; return(StatusCode(400, ErrorModel)); } } catch (Exception ex) { ErrorModel.ErrorMessage = ex.Message; ErrorModel.ErrorCode = "500"; return(StatusCode(500, ErrorModel)); } }
private async void OnInitDbClick(object sender, RoutedEventArgs e) { CountLabel.Text = ""; TimeLabel.Text = ""; List.ItemsSource = null; await Task.Delay(TimeSpan.FromMilliseconds(20)); _dataAdapter.Remove(); for (int i = 0; i < 100000; i++) { var blog = new BlogDto() { BlogId = i + 1, Url = "https://docs.microsoft.com/en-us/ef/core/get-started/uwp/getting-started" }; _dataAdapter.InsertBlogs(blog); } //Load data after initialize LoadData(); }
async public Task AddBlogAsync(BlogDto blog) { Blog blogEntity = blog.Adapt <Blog>(); blogEntity.GUID = Guid.NewGuid(); var b = Context.Blog.Add(blogEntity); Dictionary <string, Tag> existingTags = Context.Tag.Where(i => blog.Tags.Contains(i.Name)).ToDictionary(i => i.Name.ToLower()); foreach (string tag in blog.Tags) { Tag t = existingTags.ContainsKey(tag.ToLower()) ? existingTags[tag.ToLower()] : null; if (t == null) { t = new Tag() { Name = tag, Active = true, CreatedAt = DateTime.UtcNow }; } Context.BlogTag.Add(new BlogTag() { Blog = b.Entity, Tag = t, CreatedAt = DateTime.UtcNow }); } await Context.SaveChangesAsync(); blog.Id = b.Entity.Id; }
public async Task <IActionResult> CreateBlog([FromBody] BlogDto blog) { try { var result = await _blogService.CreateBlog(blog, AuthInfo()); if (result != null) { _logger.LogInformation("User successfully created a blog"); return(CreatedAtAction(nameof(GetBlogById), new { id = result.Id }, result)); } else { throw new ArgumentNullException(); } } catch (ArgumentNullException ex) { _logger.LogError(ex, ex.Message); return(BadRequest()); } catch (NameIsAlreadyTakenException ex) { _logger.LogError(ex, "User tried to create blog with name that was already taken"); return(BadRequest(ex)); } catch (Exception ex) { _logger.LogError(ex, "Error occurred while user tried to create blog"); throw; } }
public ActionResult Create(BlogViewModel vm) { if (ModelState.IsValid) { //Smestanje slike na drajv string fileName = Guid.NewGuid().ToString() + "_" + vm.Picture.FileName; string putanja = Path.Combine(Server.MapPath("~/Content/images"), fileName); vm.Picture.SaveAs(putanja); BlogDto dto = new BlogDto { Name = vm.Name, Date_created = DateTime.Now, Text = vm.Text, User_id = User.Identity.GetUserId(), Picture = new PictureDto { Alt = "blogslika", Src = "Content/Images/" + fileName } }; OpBlogInsert op = new OpBlogInsert(); op.BlogDto = dto; var result = _manager.executeOperation(op); return(RedirectToAction("Index")); } else { return(View()); } }
public OperationResult Update(BlogDto dto) { try { var validate = Validate(dto); if (validate != null) { return(validate); } Blog blog = BlogRepository.GetById(dto.id); if (blog == null) { return(new OperationResult(OperationResultType.QueryNull)); } blog = dto.MapTo(blog); BlogRepository.Update(blog); return(new OperationResult(OperationResultType.Success, "更新博客成功!")); } catch (Exception ex) { var msg = ex.Message; //log 记录异常信息 //返回用户友好的提示 return(new OperationResult(OperationResultType.Error, "更新博客失败!")); } }
public Post CreatePostWithBlog(PostWithBlog postWithBlog) { PostDto post = null; _appContext.StartSession(); try { var blog = new BlogDto() { Url = postWithBlog.BlogUrl }; _blogRepository.Create(blog); post = new PostDto() { BlogId = blog.Id, Title = postWithBlog.Title, Content = postWithBlog.Content }; _postRepository.Create(post); _appContext.CompleteSession(); } catch { _appContext.RollbackSession(); throw; } return(_mapper.Map <Post>(post)); }
public void Execute(BlogDto request, int id) { var blog = _context.Blogs.Find(id); if (blog == null) { throw new EntityNotFoundException(id, typeof(Blog)); } _context.Database.ExecuteSqlRaw($"Delete from BlogCategory where BlogId = {id}"); _validator.ValidateAndThrow(request); blog.Name = request.Name; blog.Description = request.Description; blog.ModifiedAt = DateTime.Now; var categoryIds = request.CategoryIds; ICollection <BlogCategory> blogCategories = new List <BlogCategory>(); foreach (var categoryId in categoryIds) { var blogCategory = new BlogCategory { BlogId = id, CategoryId = categoryId }; blogCategories.Add(blogCategory); } blog.BlogCategories = blogCategories; _context.SaveChanges(); }
public List <BlogDto> GetAllBlogs() { BlogManager blogManager = new BlogManager(this._unitOfWork); List <BlogDto> blogDtolsit = new List <BlogDto>(); var bloglist = blogManager.GetBlogAll(); foreach (BlogDtoDll blog in bloglist) { BlogDto blogDto = new BlogDto { BlogId = blog.BlogId, Url = blog.Url }; List <PostDto> postDtolist = new List <PostDto>(); foreach (var post in blog.PostDtoDll) { PostDto postDto = new PostDto { BlogId = post.BlogId, Content = post.Content, Title = post.Title, PostId = post.PostId }; postDtolist.Add(postDto); } blogDto.PostDto = postDtolist; blogDtolsit.Add(blogDto); } return(blogDtolsit); }
public void UpdateBlogName(int id, BlogDto blog, string token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } if (blog == null) { throw new ArgumentNullException(nameof(blog)); } var entity = _unitOfWork.BlogRepository.GetById(id); if (entity == null) { throw new ArgumentNullException(nameof(entity), "This blog doesn't exist"); } if (!ConfigureRights(token, entity.OwnerId)) { throw new NotEnoughtRightsException(); } if (_unitOfWork.BlogRepository.Get(b => b.Name == blog.Name).FirstOrDefault() != null) { throw new NameIsAlreadyTakenException(); } entity.Name = blog.Name; _unitOfWork.BlogRepository.Update(entity); _unitOfWork.Save(); }
public BlogDto GetById(int id) { BlogDto blog = null; using (var command = _blogAppContext.CreateCommand()) { command.CommandText = @"SELECT BlogId, Url FROM Blogs WHERE BlogId = @BlogId" ; var param = command.CreateParameter(); param.ParameterName = "BlogId"; param.Value = id; command.Parameters.Add(param); using (var reader = command.ExecuteReader()) { if (reader.Read()) { blog = _mapper.Map <IDataReader, BlogDto>(reader); //blog = CreateBlogFromReader(reader); } } } return(blog); }
/// <summary> /// 更新 Blog /// </summary> /// <param name="blogDto">Blog Dto</param> /// <returns></returns> public async Task <bool> UpdateAsync(BlogDto blogDto) { // Convert BlogDto to Blog var blog = this._mapper.Map <Blog>(blogDto); return(await this._blogRepository.UpdateAsync(blog)); }
/// <summary> /// 获取一条博客 /// </summary> /// <param name="blogId"></param> /// <returns></returns> public async Task <BlogDto> GetOneBlogByBlogIdAsync(long blogId) { string where = "where blog.IsDelete=0 and blog.BlogId=@BlogId"; string sql = string.Format("select blog.BlogId,blog.CategoryID,blog.Title,blog.Body,blog.Remark,blog.KeyWord,blog.Description,blog.CreateDate,blog.UpdateDate,blog.Sort,blog.UserId,blog.VisitCount,blog.CommentCount,blog.IsEssence,blog.IsHomePage,blog.IsDelete,category.CategoryID,category.CategoryName,category.CreateDate,user.UserId,user.LoginName,user.UserName,user.UserHeadImaUrl from `blog` " + " left join `category` on blog.CategoryID=category.CategoryID left join `user` on user.UserId=blog.UserId {0} ", where); List <Blog> blist = null; using (var connection = CreateConnection()) { blist = (List <Blog>) await connection.QueryAsync <Blog, Category, User, Blog>(sql, (qblog, qcategory, quser) => { qblog.Category = qcategory; qblog.User = quser; return(qblog); }, new { BlogId = blogId }, splitOn : "BlogId,CategoryId,UserId"); } BlogDto blogDto = new BlogDto(); if (blist.Count() > 0) { blogDto = Mapper.Map <Blog, BlogDto>(blist[0]); blogDto.CategoryDto = Mapper.Map <Category, CategoryDto>(blist[0].Category); blogDto.User = Mapper.Map <User, UserDto>(blist[0].User); } return(blogDto); }
public bool CreateBlog(JObject blogDto) { try { var blog = new BlogDto { BlogTitle = blogDto["BlogTitle"].ToString(), CreatedBy = blogDto["CreatedBy"].ToObject <BlogUserDto>(), CreationDate = DateTime.Now }; var result = BlogService.CreateBlog(blog); if (result == AnswerStatus.Successfull) { return(true); } else { return(false); } } catch { return(false); } }
public void Execute(BlogDto request) { _validator.ValidateAndThrow(request); ICollection <BlogCategory> categoryBlogs = new List <BlogCategory>(); foreach (var catId in request.CategoryIds) { var blogCategory = new BlogCategory { CategoryId = catId }; categoryBlogs.Add(blogCategory); } var blog = new Blog { Name = request.Name, Description = request.Description, BlogCategories = categoryBlogs, UserId = actor.Id }; _context.Blogs.Add(blog); _context.SaveChanges(); }
public ActionResult Update(int id, BlogDto Blog) { BlogModel BlogInfo = new BlogModel { blog_id = Blog.blog_id, date = Blog.date, photo_path = Blog.photo_path, title = Blog.title, text = Blog.text, email = Blog.email, ApplicationUserId = User.Identity.GetUserId() }; string url = "blogapi/updateblog/" + id; HttpContent content = new StringContent(jss.Serialize(BlogInfo)); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = client.PostAsync(url, content).Result; if (response.IsSuccessStatusCode) { return RedirectToAction("AdminShow", new { id }); } else { return RedirectToAction("Error"); } }
public async Task <ActionResult> Create(CreateBlogModel model) { if (ModelState.IsValid) { string currentUserId = HttpContext.User.Identity.GetUserId(); BlogDto blogDto = new BlogDto { Title = model.Title, Text = model.Text, CreateAt = DateTime.Now, UserProfileId = currentUserId, IsDeleted = false }; OperationDetails operationDetails = BlogService.Create(blogDto); if (operationDetails.Succedeed) { return(RedirectToAction("Index", "Blog")); } else { ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } } return(View()); }
public async Task <IActionResult> Add(int?id) { var claim = GetClaim(HttpContext.User.Claims, ClaimTypes.Sid); if (claim == null) { return(NotFound()); } int userID = int.Parse(claim.Value); ViewBag.CyList = await this._categoryService.GetAllCategoryByUserId(userID); ViewBag.NavTitle = "添加博客"; ViewBag.Btn = "添加"; BlogDto blogDto = null; if (id != null) { blogDto = await this._blogService.GetOneBlogByBlogIdAsync((int)id); ViewBag.NavTitle = "编辑博客"; ViewBag.Btn = "编辑"; } else { blogDto = new BlogDto(); } ViewBag.Blog = blogDto; return(View()); }
public async Task <IActionResult> AddBlog([FromBody] BlogDto blog) { //int n = 4; //if (n == 14) //{ // throw new Exception("Test exception", new Exception("Inner exception for testing")); //} if (blog == null) { return(BadRequest("Blog object is null.")); } if (blog.Id != 0) { return(BadRequest("Blog Id is not zero.")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else { await _blogCommands.AddBlogAsync(blog); } return(CreatedAtAction(nameof(AddBlog), blog)); }
public async Task CreateBlog(BlogDto blog) { var json = JsonConvert.SerializeObject(blog); var resp = await _httpClient.PostAsync($"/api/blogs", new StringContent(json, Encoding.UTF8, "application/json")); resp.EnsureSuccessStatusCode(); }
public ActionResult Create([Bind(Include = "Title,Body")] BlogDto blog) { if (ModelState.IsValid) { var entity = _mapper.Map <Blog>(blog); entity.UserId = (HttpContext.User.Identity as ClaimsIdentity).FindFirstValue("id"); entity.LastEditDateTime = DateTime.UtcNow; _dbContext.BLogs.Add(entity); try { _dbContext.SaveChanges(); } catch (DbUpdateException e) { Console.WriteLine(e); } return(RedirectToAction("Index")); } return(View()); }
public IActionResult Create(BlogDto blogDto) { try { if (_blogService.Insert(blogDto)) { var response = new DataResponeCommon() { Statu = StatuCodeEnum.OK, Message = "Thêm thành công" }; return(Json(response)); } else { var response = new DataResponeCommon() { Statu = StatuCodeEnum.InternalServerError, Message = "Thêm thất bại" }; return(Json(response)); } } catch (Exception e) { _logger.LogError(e.Message); throw; } }
public void update(BlogDto blog_dto) { try { using (TransactionScope tx = new TransactionScope(TransactionScopeOption.Required)) { Blog blogs = _blogRepository.getById(blog_dto.blog_id); if (blogs == null) { throw new ItemNotFoundException($"Blog with ID {blog_dto.blog_id} doesnot Exit."); } if (blog_dto.image_name == null) { blog_dto.image_name = blogs.image_name; } _blogMaker.copy(ref blogs, blog_dto); _blogRepository.update(blogs); tx.Complete(); } } catch (Exception) { throw; } }
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); }
/// <summary> /// 新增 Blog /// </summary> /// <param name="blogDto">Blog Dto</param> /// <returns></returns> public async Task <int> AddAsync(BlogDto blogDto) { // Convert BlogDto to Blog var blog = this._mapper.Map <Blog>(blogDto); return(await this._blogRepository.AddAsync(blog));; }
public void BlogCRUD() { Task.Run(async() => { //await _blogMng.DeleteBlogAsync(2010); string blogName01 = "testBlog01"; int primaryAuthorId = 1; List <string> tags = new List <string>() { "Programming", "Art" }; BlogDto blogDto = new BlogDto() { Name = "myTestBlog", DisplayName = "My Test Blog", Description = "My test blog description", DisplayOrder = 1, BlogStatusId = (int)BlogStatuses.Draft, PrimaryAuthorId = primaryAuthorId }; blogDto.Tags.AddRange(tags); await _blogCmds.AddBlogAsync(blogDto); BlogDto blogToUpdate = _blogRqs.GetBlog(blogDto.Id); blogToUpdate.Name = blogName01; blogDto.Name = blogName01; await _blogCmds.UpdateBlogAsync(blogDto); blogToUpdate = _blogRqs.GetBlog(blogToUpdate.Id); Assert.AreEqual(blogToUpdate.Name, blogName01); blogToUpdate = _blogRqs.GetBlog(blogName01); Assert.AreEqual(blogToUpdate.Name, blogName01); var blogs = await _blogRqs.GetBlogs(tags, BlogStatuses.Draft); Assert.IsTrue(blogs.Count() > 0); blogs = await _blogRqs.GetBlogsByAuthor(primaryAuthorId, BlogStatuses.Draft); Assert.IsTrue(blogs.Count() > 0); await _blogCmds.UpdateBlogStatusAsync(blogToUpdate.Id, BlogStatuses.Published); blogs = await _blogRqs.GetBlogsByAuthor(primaryAuthorId, BlogStatuses.Published); Assert.IsTrue(blogs.Count() > 0); blogs = await _blogRqs.GetBlogsByAuthor(primaryAuthorId); Assert.IsTrue(blogs.Count() > 0); blogs = await _blogRqs.FindBlogs("TestBlog"); Assert.IsTrue(blogs.Count() > 0); blogs = await _blogRqs.FindBlogs("TestBlog", BlogStatuses.Published); Assert.IsTrue(blogs.Count() > 0); await _blogCmds.DeleteBlogAsync(blogToUpdate.Id); blogToUpdate = _blogRqs.GetBlog(blogToUpdate.Id); Assert.IsNull(blogToUpdate); }).GetAwaiter().GetResult(); }
public HttpResponseMessage Put(BlogDto blog) { var validationService = new BlogValidation(); var results = validationService.Validate(blog); if (!results.IsValid) { return ValidationHelper.FailedValidationMessage(results); } _blogService.Create(blog); return new HttpResponseMessage(HttpStatusCode.OK); }
public void Blog_Must_Validate_And_Return_Message() { // Arrange var controller = new BlogController(); var blog = new BlogDto(); // Act var result = controller.Put(blog); // Assert Assert.AreEqual(result.StatusCode, HttpStatusCode.BadRequest); }
public void Put_Valid_Blog_Test() { // Arrange var controller = new BlogController(); var blog = new BlogDto(); blog.AuthorName = "somename"; blog.Title = "SomeTitle"; // Act var result = controller.Put(blog); // Assert Assert.AreEqual(result.StatusCode, HttpStatusCode.OK); }
public OperationResult Add(BlogDto dto) { try { var validate = Validate(dto); if (validate != null) return validate; Blog blog = dto.MapTo<Blog>(); blog.createTime = DateTime.Now; BlogRepository.Insert(blog); return new OperationResult(OperationResultType.Success, "添加博客成功!"); } catch (Exception ex) { var msg = ex.Message; //log 记录异常信息 //返回用户友好的提示 return new OperationResult(OperationResultType.Error, "添加博客失败!"); } }
public HttpResponseMessage PostBlog(BlogDto blog) { return Request.CreateResponse(HttpStatusCode.Created); }
private OperationResult Validate(BlogDto dto) { if (dto.title.IsNullOrEmpty() || dto.title.Trim().IsNullOrEmpty()) { return new OperationResult(OperationResultType.ValidError, "博客标题不能为空!"); } return null; }
public BlogDto GetByKey(int id) { var blog = this.Entities.FirstOrDefault(w => w.Id == id); if (blog != null) { var dto = new BlogDto() { id = blog.Id, title = blog.title }; return dto; } return null; }