public async Task UpdateCategoriesAsync(BlogPostEntity blogPostEntity, IEnumerable <CategoryEntity> blogPostCategories) { var existingCategories = blogPostEntity.BlogCategoryEntities.Select(c => c.Category); // Added var addedCategories = blogPostCategories .Where(c => existingCategories.All(ic => ic.Id != c.Id)); // Removed var removedCategories = existingCategories .Where(c => blogPostCategories.All(ic => ic.Id != c.Id)); if (removedCategories.Any()) { this.Context.BlogCategories.RemoveRange(removedCategories.Select(c => new BlogCategoryEntity { BlogPostId = blogPostEntity.Id, CategoryId = c.Id })); } if (addedCategories.Any()) { await this.Context.BlogCategories.AddRangeAsync(addedCategories.Select(c => new BlogCategoryEntity { BlogPostId = blogPostEntity.Id, CategoryId = c.Id })); } await this.Context.SaveChangesAsync(); }
public void ShouldRemoveBlogPost() { // Arrange var entity = new BlogPostEntity(_procedures); // Act var dataRemoved = entity.Remove(_data); // Assert Check.That(dataRemoved).IsTrue(); Check.That(_procedures.Received().Remove(_data)); }
public void ShouldEditBlogPost() { // Arrange var entity = new BlogPostEntity(_procedures); // Act var addedData = entity.Edit(_data); // Assert Check.That(addedData).IsNotNull().And.IsEqualTo(_data); Check.That(_procedures.Received().Edit(_data)); }
public async Task <HttpResponseMessage> PostDeleteBlogPostEntityAsync(BlogPostEntity blogPost) { try { return(await _client.PostAsJsonAsync( "DeleteBlogPost", blogPost)); } catch { return(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)); } }
public async Task <HttpResponseMessage> PostBlogPostAsync(BlogPostEntity blogPost) { try { return(await _client.PostAsJsonAsync( "InsertOrMergeBlogPost", blogPost)); } catch (Exception e) { Console.WriteLine(e); return(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)); } }
public BlogPost MapToBlogPost(BlogPostEntity model, BlogCategoryEntity category, List <BlogPostTagEntity> tags) { var result = new BlogPost() { ID = model.Id, PublishedDate = model.Created.Date, Title = model.Data.Title, Body = model.Data.Body, Category = MapToBlogCategory(category), Tags = MapToBlogPostTags(tags) }; return(result); }
public BlogPost MapToBlogPost(BlogPostEntity model, List <SkillTypeEntity> skills) { var result = new BlogPost() { Id = model.Id, PublishedDate = model.Created.Date, ImageUrl = ResolveAssetURL(model.Data.Image.First()), Title = model.Data.Title, Body = model.Data.Body, Skills = MapToSkills(skills) }; return(result); }
/// <summary> /// Initializes the service. /// </summary> /// <returns>A task which initializes the service.</returns> public async Task InitAsync() { CatalogLastQueried = await _localStorage.GetItemAsync <DateTime>(catalogLastQueriedKey); TableMetadata = await _client.GetTableMetadataAsync(blogPostsTableName); PartitionKeys = await _localStorage.GetItemAsync <string[]>(partitionKeysKey); RowKeys = await _localStorage.GetItemAsync <string[]>(rowKeysKey); if ((PartitionKeys == null) || (RowKeys == null) || (CatalogLastQueried.Ticks == 0) || (CatalogLastQueried < TableMetadata.Timestamp)) { QueryBlogPostEntitiesResponse response = await _client.GetQueryBlogPostsResponseAsync( takeCount : 1000, selectColumns : new List <string>() { "PartitionKey", "RowKey" }); PartitionKeys = new string[response.BlogPosts.Count]; RowKeys = new string[response.BlogPosts.Count]; for (int i = 0; i < response.BlogPosts.Count; i++) { PartitionKeys[i] = response.BlogPosts[i].PartitionKey; RowKeys[i] = response.BlogPosts[i].RowKey; } await _localStorage.SetItemAsync(catalogLastQueriedKey, DateTime.UtcNow); await _localStorage.SetItemAsync(partitionKeysKey, PartitionKeys); await _localStorage.SetItemAsync(rowKeysKey, RowKeys); } else { BlogPosts = await _localStorage.GetItemAsync <BlogPostEntity[][]>(blogPostsKey); } if (BlogPosts?.Length != NumOfPages) { BlogPosts = new BlogPostEntity[NumOfPages][]; } HasNotInitialized = false; }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var blogPost = new BlogPostEntity { CreatedAt = DateTime.UtcNow, Title = BlogPost.Title, Body = BlogPost.Body, Comments = new List <CommentEntity>() }; var tagList = new string [] {}; if (!string.IsNullOrEmpty(BlogPost.Tags)) { tagList = BlogPost.Tags.Split(","); } var tagEntities = new List <TagEntity>(); // Initialise slugify helper var helper = new SlugHelper(); foreach (var tag in tagList) { var urlSlug = helper.GenerateSlug(tag); var tagEntity = new TagEntity { BlogPostId = blogPost.Id, DisplayName = tag, UrlFragment = urlSlug }; tagEntities.Add(tagEntity); } blogPost.Tags = tagEntities; _blogDbContext.BlogPosts.Add(blogPost); await _blogDbContext.SaveChangesAsync(); return(RedirectToPage("/Index", new { area = "admin" })); }
public void ToBlogPostTest() { var entity = new BlogPostEntity { Id = "id123", Title = "Title", BodyHtml = "Hello", PublishedAt = new DateTime(2021, 1, 1) }; var result = entity.ToBlogPost(); Assert.Equal( new BlogPost("Title", "id123", "Hello", new DateTime(2021, 1, 1)), result); }
public async Task <BlogPostEntity> CreatePostAsync(BlogPost post, string userId, CancellationToken ct) { var postEntity = new BlogPostEntity() { ApplicationUserId = userId, Content = post.Content, Id = Guid.NewGuid(), Image = post.Image, Title = post.Title, CreatedDate = DateTimeOffset.Now, ModifiedDate = DateTimeOffset.Now, Comments = new Collection <CommentEntity>() }; _context.BlogPosts.Add(postEntity); await _context.SaveChangesAsync(ct); return(postEntity); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [Table("blogposts", "AzureWebJobsStorage")] CloudTable blogPostsTable, [Table("metadata", "AzureWebJobsStorage")] CloudTable metadataTable, ILogger log) { try { BlogPostEntity blogPost = JsonConvert.DeserializeObject <BlogPostEntity>( await req.ReadAsStringAsync() ); if (!blogPost.IsValid) { return(new BadRequestErrorMessageResult("The BlogPostEntity.IsValid check failed.")); } else if ( ((await _jwtService.GetClaimsPrincipalAsync(req)) .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value != blogPost.AuthorOID) || string.IsNullOrEmpty(blogPost.AuthorOID)) { // "oid" claim is invalid. return(new UnauthorizedResult()); } // Insert or merge the blog post. TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(blogPost); await blogPostsTable.ExecuteAsync(insertOrMergeOperation); // Update metadata. TableOperation insertOrMergeMetadata = TableOperation.InsertOrMerge(new TableMetadataEntity("blogposts")); await metadataTable.ExecuteAsync(insertOrMergeMetadata); return(new OkResult()); } catch (Exception e) { log.LogError($"function InsertOrMergeBlogPost -- caught exception {e} {e.Message} {e.StackTrace}"); return(new InternalServerErrorResult()); } }
public BlogPost MapToBlogPost(BlogPostEntity model, AuthorEntity author) { var result = new BlogPost() { Id = model.Id, PublishedDate = model.Data.PublishDate, ImageHeaderUrl = ResolveAssetURL(model.Data.ImageHeader.First()), Title = model.Data.Title, Tags = model.Data.Tags, SubTitle = model.Data.SubTitle, BodyHtml = model.Data.BodyHtml, MetaDescription = model.Data.MetaDescription, Author = new Author() { Name = author.Data.Name, Link = author.Data.Link } }; return(result); }
private static async Task MainAsync(CancellationToken cancellation) { try { var client = new DocumentClient(new Uri(MyCosmosUri), MyCosmosKey); var adapter = new DemoAdapter(client, MyDatabaseName, MyCollectionName); AuthorEntity author = await adapter.Authors.UpsertAsync( new AuthorEntity { Name = "david" }, cancellation); BlogPostEntity blogPost = await adapter.BlogPosts.UpsertAsync( new BlogPostEntity { AuthorId = author.Id, Text = "hello" }, cancellation); IList <AuthorEntity> allAuthors = await adapter.Authors.ListAllAsync(cancellation); IList <BlogPostEntity> firstAuthorPosts = await adapter.BlogPosts.ListByAuthorAsync(allAuthors[0].Id, cancellation); Console.WriteLine($"Posts by author '{allAuthors[0].Id}':"); Console.WriteLine(JsonConvert.SerializeObject(firstAuthorPosts, Formatting.Indented)); Console.WriteLine(); Console.WriteLine("Metrics:"); Console.WriteLine($" Total charge: {adapter.TotalCharge} RU's"); Console.WriteLine($" Total requests: {adapter.TotalRequests}"); } catch (Exception ex) { Console.WriteLine("An error occurred:"); Console.Write(ex.ToString()); } }