Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code refact and improve EF performance #35

Merged
merged 4 commits into from
Feb 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/Moonglade.Core/CategoryService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edi.Practice.RequestResponseModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moonglade.Data;
using Moonglade.Data.Entities;
Expand All @@ -19,7 +21,7 @@ public Response<List<Category>> GetAllCategories()
{
try
{
var item = Context.Category.ToList();
var item = Context.Category.AsNoTracking().ToList();
return new SuccessResponse<List<Category>>(item);
}
catch (Exception e)
Expand Down Expand Up @@ -59,7 +61,7 @@ public Response<Category> GetCategory(Guid categoryId)
}
}

public Response<List<CategoryInfo>> GetCategoryList()
public async Task<Response<List<CategoryInfo>>> GetCategoryListAsync()
{
try
{
Expand All @@ -69,19 +71,19 @@ public Response<List<CategoryInfo>> GetCategoryList()
DisplayName = c.DisplayName,
Name = c.Title,
Note = c.Note
});
}).AsNoTracking();

var list = query.ToList();
var list = await query.ToListAsync();
return new SuccessResponse<List<CategoryInfo>>(list);
}
catch (Exception e)
{
Logger.LogError(e, $"Error {nameof(GetCategoryList)}");
Logger.LogError(e, $"Error {nameof(GetCategoryListAsync)}");
return new FailedResponse<List<CategoryInfo>>((int)ResponseFailureCode.GeneralException);
}
}

public Response<List<ArchiveItem>> GetArchiveList()
public async Task<Response<List<ArchiveItem>>> GetArchiveListAsync()
{
try
{
Expand All @@ -104,12 +106,12 @@ into monthList
Count = monthList.Select(p => p.Id).Count()
};

var list = query.ToList();
var list = await query.ToListAsync();
return new SuccessResponse<List<ArchiveItem>>(list);
}
catch (Exception e)
{
Logger.LogError(e, $"Error {nameof(GetArchiveList)}");
Logger.LogError(e, $"Error {nameof(GetArchiveListAsync)}");
return new FailedResponse<List<ArchiveItem>>((int)ResponseFailureCode.GeneralException);
}
}
Expand Down
18 changes: 10 additions & 8 deletions src/Moonglade.Core/CommentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using Edi.Practice.RequestResponseModel;
using Edi.WordFilter;
Expand Down Expand Up @@ -30,32 +31,33 @@ public CommentService(MoongladeDbContext context,
_blogConfig.GetConfiguration(blogConfigurationService);
}

public Response<List<Comment>> GetRecentComments()
public async Task<Response<List<Comment>>> GetRecentCommentsAsync(int top)
{
try
{
var recentComments = Context.Comment.Include(c => c.Post)
.ThenInclude(p => p.PostPublish)
.Where(c => c.IsApproved.Value)
.OrderByDescending(c => c.CreateOnUtc)
.Take(AppSettings.RecentCommentsListSize);
.Take(top)
.AsNoTracking();

var list = recentComments.ToList();
var list = await recentComments.ToListAsync();
return new SuccessResponse<List<Comment>>(list);
}
catch (Exception e)
{
Logger.LogError(e, $"Error {nameof(GetRecentComments)}");
Logger.LogError(e, $"Error {nameof(GetRecentCommentsAsync)}");
return new FailedResponse<List<Comment>>((int)ResponseFailureCode.GeneralException);
}
}

public IEnumerable<Comment> GetApprovedCommentsOfPost(Guid postId)
public List<Comment> GetApprovedCommentsOfPost(Guid postId)
{
var comments = Context.Comment.Include(c => c.CommentReply)
.Where(c => c.PostId == postId &&
c.IsApproved != null &&
c.IsApproved.Value);
.Where(c => c.PostId == postId &&
c.IsApproved != null &&
c.IsApproved.Value).ToList();
return comments;
}

Expand Down
8 changes: 7 additions & 1 deletion src/Moonglade.Core/EmailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ public EmailService(MoongladeDbContext context,
_blogConfig.GetConfiguration(blogConfigurationService);

var configSource = $@"{AppDomain.CurrentDomain.GetData(Constants.AppBaseDirectory)}\mailConfiguration.xml";
if (!File.Exists(configSource))
{
throw new FileNotFoundException("Configuration file for EmailHelper is not present.", configSource);
}

if (EmailHelper == null)
{
Expand All @@ -47,7 +51,9 @@ public EmailService(MoongladeDbContext context,
EmailHelper.EmailSent += (sender, eventArgs) =>
{
if (sender is MailMessage msg)
{
Logger.LogInformation($"Email {msg.Subject} is sent, Success: {eventArgs.IsSuccess}");
}
};
}
}
Expand Down Expand Up @@ -92,7 +98,7 @@ public async Task SendNewCommentNotificationAsync(Comment comment, string postTi
var pipeline = new TemplatePipeline().Map("Username", comment.Username)
.Map("Email", comment.Email)
.Map("IPAddress", comment.IPAddress)
.Map("PubDate", comment.CreateOnUtc.ToString("yyyy-MM-dd HH:mm"))
.Map("PubDateUtc", comment.CreateOnUtc.ToString("MM/dd/yyyy HH:mm"))
.Map("Title", postTitle)
.Map("CommentContent", comment.CommentContent);

Expand Down
8 changes: 5 additions & 3 deletions src/Moonglade.Core/FriendLinkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Edi.Practice.RequestResponseModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moonglade.Data;
Expand Down Expand Up @@ -33,16 +35,16 @@ public Response<FriendLink> GetFriendLink(Guid id)
}
}

public Response<List<FriendLink>> GetAllFriendLinks()
public async Task<Response<List<FriendLink>>> GetAllFriendLinksAsync()
{
try
{
var item = Context.FriendLink.ToList();
var item = await Context.FriendLink.AsNoTracking().ToListAsync();
return new SuccessResponse<List<FriendLink>>(item);
}
catch (Exception e)
{
Logger.LogError(e, $"Error {nameof(GetAllFriendLinks)}");
Logger.LogError(e, $"Error {nameof(GetAllFriendLinksAsync)}");
return new FailedResponse<List<FriendLink>>((int)ResponseFailureCode.GeneralException);
}
}
Expand Down
47 changes: 23 additions & 24 deletions src/Moonglade.Core/PostService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public IQueryable<Post> GetPostsAsQueryable()
return Context.Post.Include(p => p.PostPublish).Include(p => p.PostExtension);
}

public IEnumerable<Post> GetPagedPost(int pageSize, int pageIndex, Guid? categoryId = null)
public IQueryable<Post> GetPagedPost(int pageSize, int pageIndex, Guid? categoryId = null)
{
if (pageSize < 1)
{
Expand All @@ -110,7 +110,7 @@ public IEnumerable<Post> GetPagedPost(int pageSize, int pageIndex, Guid? categor
return GetPagedPosts(pageSize, pageIndex, categoryId);
}

public IEnumerable<Post> GetPagedPosts(int pageSize, int pageIndex, Guid? categoryId = null)
public IQueryable<Post> GetPagedPosts(int pageSize, int pageIndex, Guid? categoryId = null)
{
var startRow = (pageIndex - 1) * pageSize;
var query = Context.Post.Where(p => !p.PostPublish.IsDeleted &&
Expand Down Expand Up @@ -338,7 +338,6 @@ public Response EditPost(Post postModel, List<string> tags, List<Guid> categoryI
if (!postModel.PostPublish.PubDateUtc.HasValue)
{
postModel.PostPublish.PubDateUtc = DateTime.UtcNow;
postModel.PostPublish.PubDateUtc = DateTime.UtcNow.ToUniversalTime();
}

// 1. Add new tags to tag lib
Expand Down Expand Up @@ -395,27 +394,6 @@ public Response EditPost(Post postModel, List<string> tags, List<Guid> categoryI
}
}

private static void ApplyDefaultValuesOnPost(Post postModel)
{
if (postModel.Id == Guid.Empty)
{
postModel.Id = Guid.NewGuid();
}
if (string.IsNullOrWhiteSpace(postModel.Slug))
{
postModel.Slug = postModel.Id.ToString();
}

if (null == postModel.PostExtension)
{
postModel.PostExtension = new PostExtension
{
Hits = 0,
Likes = 0
};
}
}

public Response RestoreFromRecycle(Guid postId)
{
try
Expand Down Expand Up @@ -462,5 +440,26 @@ public Response Delete(Guid postId, bool isRecycle = false)
return new FailedResponse((int)ResponseFailureCode.GeneralException);
}
}

private static void ApplyDefaultValuesOnPost(Post postModel)
{
if (postModel.Id == Guid.Empty)
{
postModel.Id = Guid.NewGuid();
}
if (string.IsNullOrWhiteSpace(postModel.Slug))
{
postModel.Slug = postModel.Id.ToString();
}

if (null == postModel.PostExtension)
{
postModel.PostExtension = new PostExtension
{
Hits = 0,
Likes = 0
};
}
}
}
}
10 changes: 4 additions & 6 deletions src/Moonglade.Core/SyndicationFeedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public async Task RefreshRssFilesForCategoryAsync(string categoryName)
var cat = Context.Category.FirstOrDefault(c => c.Title == categoryName);
if (null != cat)
{
var itemCollection = GetPostsAsRssFeedItems(cat.Id);
var itemCollection = GetPostsAsFeedItems(cat.Id);

var rw = new SyndicationFeedGenerator
{
Expand All @@ -56,9 +56,7 @@ public async Task RefreshRssFilesForCategoryAsync(string categoryName)
MaxContentLength = 0
};

Logger.LogInformation($"Writing RSS file for category id {cat.Id}");
await rw.WriteRss20FileAsync($@"{AppDomain.CurrentDomain.GetData(Constants.DataDirectory)}\feed\posts-category-{categoryName}.xml");

Logger.LogInformation($"Finished refreshing RSS feed for category {categoryName}.");
}
else
Expand All @@ -70,7 +68,7 @@ public async Task RefreshRssFilesForCategoryAsync(string categoryName)
public async Task RefreshFeedFileForPostAsync(bool isAtom)
{
Logger.LogInformation("Start refreshing feed for posts.");
List<SimpleFeedItem> itemCollection = GetPostsAsRssFeedItems();
List<SimpleFeedItem> itemCollection = GetPostsAsFeedItems();

var rw = new SyndicationFeedGenerator
{
Expand Down Expand Up @@ -98,9 +96,9 @@ public async Task RefreshFeedFileForPostAsync(bool isAtom)
Logger.LogInformation("Finished writing feed for posts.");
}

private List<SimpleFeedItem> GetPostsAsRssFeedItems(Guid? categoryId = null)
private List<SimpleFeedItem> GetPostsAsFeedItems(Guid? categoryId = null)
{
Logger.LogInformation($"{nameof(GetPostsAsRssFeedItems)} - {nameof(categoryId)}: {categoryId}");
Logger.LogInformation($"{nameof(GetPostsAsFeedItems)} - {nameof(categoryId)}: {categoryId}");

int? top = null;
if (_blogConfig.FeedSettings.RssItemCount != 0)
Expand Down
10 changes: 6 additions & 4 deletions src/Moonglade.Core/TagService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edi.Practice.RequestResponseModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moonglade.Data;
using Moonglade.Data.Entities;
Expand Down Expand Up @@ -79,22 +81,22 @@ public Response Delete(int tagId)
}
}

public Response<List<TagInfo>> GetHotTags(int top)
public async Task<Response<List<TagInfo>>> GetHotTagsAsync(int top)
{
try
{
if (Context.Tag.Any())
{
var hotTags = Context.Tag.OrderByDescending(p => p.PostTag.Count)
.Take(top)
.Take(top).AsNoTracking()
.Select(t => new TagInfo
{
TagCount = t.PostTag.Count,
TagName = t.DisplayName,
NormalizedTagName = t.NormalizedName
});

var list = hotTags.ToList();
var list = await hotTags.ToListAsync();
return new SuccessResponse<List<TagInfo>>(list);
}

Expand All @@ -115,7 +117,7 @@ public Tag GetTag(string normalizedName)

public List<TagInfo> GetTagCountList()
{
var queryTag = from tag in Context.Tag
var queryTag = from tag in Context.Tag.AsNoTracking()
select new TagInfo
{
TagName = tag.DisplayName,
Expand Down
2 changes: 1 addition & 1 deletion src/Moonglade.Model/CommentGridModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ public class CommentGridModel
public string IpAddress { get; set; }
public string CommentContent { get; set; }
public string PostTitle { get; set; }
public DateTime? PubDate { get; set; }
public DateTime? PubDateUtc { get; set; }
}
}
14 changes: 5 additions & 9 deletions src/Moonglade.Web/Controllers/ArchiveController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -30,17 +31,12 @@ public ArchiveController(MoongladeDbContext context,
}

[Route("archive")]
public IActionResult Index()
public async Task<IActionResult> Index()
{
var response = _categoryService.GetArchiveList();
if (response.IsSuccess)
{
return View(response.Item);
}

return ServerError();
var response = await _categoryService.GetArchiveListAsync();
return response.IsSuccess ? View(response.Item) : ServerError();
}

[Route("archive/{year:int:length(4)}")]
[Route("archive/{year:int:length(4)}/{month:int:range(1,12)}")]
public IActionResult GetArchiveByTime(int year, int? month)
Expand Down
3 changes: 0 additions & 3 deletions src/Moonglade.Web/Controllers/CategoryController.Manage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,6 @@ public IActionResult Edit(CategoryEditViewModel model)
DisplayName = model.DisplayName
};

var catJson = JsonConvert.SerializeObject(category);
Logger.LogInformation($"Editing category: {catJson}");

var response = _categoryService.UpdateCategory(category);

if (response.IsSuccess)
Expand Down
Loading