diff --git a/MyApp.ServiceInterface/AdminServices.cs b/MyApp.ServiceInterface/AdminServices.cs index 1572cba..43d2cb4 100644 --- a/MyApp.ServiceInterface/AdminServices.cs +++ b/MyApp.ServiceInterface/AdminServices.cs @@ -94,11 +94,11 @@ public async Task Any(AdminResetCommonPassword request) throw HttpError.NotFound("Post not found"); var refId = $"{request.Id}"; - await Db.SaveAsync(post); - var statTotal = await Db.SingleAsync(Db.From().Where(x => x.Id == refId)); + Db.Save(post); + var statTotal = Db.Single(Db.From().Where(x => x.Id == refId)); if (statTotal != null) { - await Db.InsertAsync(new StatTotals + Db.Insert(new StatTotals { Id = refId, PostId = post.Id, @@ -121,7 +121,7 @@ public async Task Any(RankAnswer request) throw HttpError.NotFound("Answer not found"); var answerCreator = !string.IsNullOrEmpty(answer.CreatedBy) - ? await Db.ScalarAsync(Db.From().Where(x => x.UserName == answer.CreatedBy).Select(x => x.Id)) + ? Db.Scalar(Db.From().Where(x => x.UserName == answer.CreatedBy).Select(x => x.Id)) : null; if (answerCreator == null) diff --git a/MyApp.ServiceInterface/AiServerServices.cs b/MyApp.ServiceInterface/AiServerServices.cs index 98459c4..2ab87e4 100644 --- a/MyApp.ServiceInterface/AiServerServices.cs +++ b/MyApp.ServiceInterface/AiServerServices.cs @@ -106,7 +106,7 @@ public async Task Any(CreateAnswerCallback request) LastUpdated = DateTime.UtcNow, }); - await Db.NotifyQuestionAuthorIfRequiredAsync(jobs, answer); + Db.NotifyQuestionAuthorIfRequired(jobs, answer); jobs.RunCommand(new CreateRankAnswerTask { AnswerId = answer.RefId!, @@ -120,7 +120,7 @@ public async Task Any(CreateAnswerCallback request) public async Task Any(RankAnswerCallback request) { - var answerCreator = await AssertUserNameById(request.UserId); + var answerCreator = AssertUserNameById(request.UserId); var graderUser = appConfig.GetModelUser(request.Grader); if (graderUser?.UserName == null) @@ -182,7 +182,7 @@ public async Task Any(RankAnswerCallback request) public async Task Any(AnswerCommentCallback request) { - var commentCreator = await AssertUserNameById(request.UserId); + var commentCreator = AssertUserNameById(request.UserId); var postId = request.AnswerId.LeftPart('-').ToInt(); var modelUserName = request.AnswerId.RightPart('-'); @@ -226,10 +226,10 @@ public async Task Any(AnswerCommentCallback request) await questions.SaveMetaAsync(postId, meta); } - private async Task AssertUserNameById(string userId) + private string AssertUserNameById(string userId) { var userName = appConfig.GetModelUserById(userId)?.UserName - ?? await Db.ScalarAsync(Db.From().Where(x => x.Id == userId).Select(x => x.UserName)); + ?? Db.Scalar(Db.From().Where(x => x.Id == userId).Select(x => x.UserName)); if (userName == null) throw HttpError.BadRequest("Invalid User Id: " + userId); return userName; diff --git a/MyApp.ServiceInterface/AnalyticsTasksCommand.cs b/MyApp.ServiceInterface/AnalyticsTasksCommand.cs index cec4b16..22682ed 100644 --- a/MyApp.ServiceInterface/AnalyticsTasksCommand.cs +++ b/MyApp.ServiceInterface/AnalyticsTasksCommand.cs @@ -1,34 +1,34 @@ using MyApp.Data; using MyApp.ServiceModel; using ServiceStack; -using ServiceStack.IO; +using ServiceStack.Data; using ServiceStack.OrmLite; namespace MyApp.ServiceInterface; [Worker(Databases.Analytics)] -public class AnalyticsTasksCommand(R2VirtualFiles r2, QuestionsProvider questions) : AsyncCommand +public class AnalyticsTasksCommand(IDbConnectionFactory dbFactory) : SyncCommand { - protected override async Task RunAsync(AnalyticsTasks request, CancellationToken token) + protected override void Run(AnalyticsTasks request) { if (request.CreatePostStat == null && request.CreateSearchStat == null && request.DeletePost == null) return; - using var analyticsDb = HostContext.AppHost.GetDbConnection(Databases.Analytics); + using var analyticsDb = dbFactory.Open(Databases.Analytics); if (request.CreatePostStat != null)// && !Stats.IsAdminOrModerator(request.RecordPostView.UserName)) { - await analyticsDb.InsertAsync(request.CreatePostStat, token: token); + analyticsDb.Insert(request.CreatePostStat); } if (request.CreateSearchStat != null)// && !Stats.IsAdminOrModerator(request.RecordSearchView.UserName)) { - await analyticsDb.InsertAsync(request.CreateSearchStat, token: token); + analyticsDb.Insert(request.CreateSearchStat); } if (request.DeletePost != null) { - await analyticsDb.DeleteAsync(x => x.PostId == request.DeletePost, token: token); + analyticsDb.Delete(x => x.PostId == request.DeletePost); } } } diff --git a/MyApp.ServiceInterface/ApiServices.cs b/MyApp.ServiceInterface/ApiServices.cs index 3d8163c..5e5e1a4 100644 --- a/MyApp.ServiceInterface/ApiServices.cs +++ b/MyApp.ServiceInterface/ApiServices.cs @@ -8,9 +8,9 @@ namespace MyApp.ServiceInterface; public class ApiServices(IDbConnectionFactory dbFactory) : Service { - public async Task Any(SearchPosts request) + public object Any(SearchPosts request) { - using var dbSearch = await dbFactory.OpenAsync(Databases.Search); + using var dbSearch = dbFactory.Open(Databases.Search); var skip = request.Skip; var take = Math.Min(request.Take ?? 25, 200); @@ -31,14 +31,14 @@ public async Task Any(SearchPosts request) q.OrderByView(request.View); - List postsFts = await dbSearch.SelectAsync(q + List postsFts = dbSearch.Select(q .Select("RefId, substring(Body,0,400) as Body, ModifiedDate") .Skip(request.Skip) .Take(take)); var total = dbSearch.Count(q); - using var db = await dbFactory.OpenAsync(); - var posts = await db.PopulatePostsAsync(postsFts); + using var db = dbFactory.Open(); + var posts = db.PopulatePosts(postsFts); return new SearchPostsResponse { @@ -48,10 +48,10 @@ public async Task Any(SearchPosts request) } else { - using var db = await dbFactory.OpenAsync(); + using var db = dbFactory.Open(); var q = db.From(); - var posts = await db.SelectAsync(q + var posts = db.Select(q .OrderByView(request.View) .Skip(skip) .Take(take)); diff --git a/MyApp.ServiceInterface/App/CreateAnswerCommand.cs b/MyApp.ServiceInterface/App/CreateAnswerCommand.cs index 201aba7..c7095bb 100644 --- a/MyApp.ServiceInterface/App/CreateAnswerCommand.cs +++ b/MyApp.ServiceInterface/App/CreateAnswerCommand.cs @@ -8,9 +8,9 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Answers)] [Worker(Databases.App)] -public class CreateAnswerCommand(AppConfig appConfig, IDbConnection db) : IAsyncCommand +public class CreateAnswerCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - public async Task ExecuteAsync(Post answer) + protected override void Run(Post answer) { if (answer.ParentId == null) throw new ArgumentNullException(nameof(answer.ParentId)); @@ -19,9 +19,9 @@ public async Task ExecuteAsync(Post answer) var postId = answer.ParentId!.Value; var refId = $"{postId}-{answer.CreatedBy}"; - if (!await db.ExistsAsync(db.From().Where(x => x.Id == refId))) + if (!db.Exists(db.From().Where(x => x.Id == refId))) { - await db.InsertAsync(new StatTotals + db.Insert(new StatTotals { Id = refId, PostId = postId, @@ -34,13 +34,13 @@ await db.InsertAsync(new StatTotals }); } - var post = await db.SingleByIdAsync(postId); + var post = db.SingleById(postId); if (post?.CreatedBy != null) { // Notify Post Author of new Answer if (post.CreatedBy != answer.CreatedBy && appConfig.IsHuman(post.CreatedBy)) { - await db.InsertAsync(new Notification + db.Insert(new Notification { UserName = post.CreatedBy, Type = NotificationType.NewAnswer, @@ -61,7 +61,7 @@ await db.InsertAsync(new Notification .Where(x => x != post.CreatedBy && x != answer.CreatedBy && appConfig.IsHuman(x)).ToList(); if (userNameMentions.Count > 0) { - var existingUsers = await db.SelectAsync(db.From() + var existingUsers = db.Select(db.From() .Where(x => userNameMentions.Contains(x.UserName!))); foreach (var existingUser in existingUsers) @@ -72,7 +72,7 @@ await db.InsertAsync(new Notification var startPos = Math.Max(0, firstMentionPos - 50); if (appConfig.IsHuman(existingUser.UserName)) { - await db.InsertAsync(new Notification + db.Insert(new Notification { UserName = existingUser.UserName!, Type = NotificationType.AnswerMention, @@ -91,7 +91,7 @@ await db.InsertAsync(new Notification if (appConfig.IsHuman(answer.CreatedBy)) { - await db.InsertAsync(new Achievement + db.Insert(new Achievement { UserName = answer.CreatedBy, Type = AchievementType.NewAnswer, diff --git a/MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs b/MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs index 6dd0dcf..25707be 100644 --- a/MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs +++ b/MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs @@ -7,6 +7,7 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Database)] +[Worker(Databases.App)] public class CreateCommentVoteCommand(IDbConnection db, QuestionsProvider questions) : IAsyncCommand { public async Task ExecuteAsync(Vote vote) @@ -16,7 +17,7 @@ public async Task ExecuteAsync(Vote vote) if (string.IsNullOrEmpty(vote.UserName)) throw new ArgumentNullException(nameof(vote.UserName)); - var rowsDeleted = await db.DeleteAsync(new { vote.RefId, vote.UserName }); + var rowsDeleted = db.Delete(new { vote.RefId, vote.UserName }); var meta = await questions.GetMetaAsync(vote.PostId); var created = vote.RefId.LastRightPart('-').ToLong(); @@ -30,9 +31,9 @@ public async Task ExecuteAsync(Vote vote) throw new ArgumentException("Can't vote on your own comment", nameof(vote.RefId)); vote.RefUserName = comment.CreatedBy; - await db.InsertAsync(vote); + db.Insert(vote); - comment.UpVotes = (int) await db.CountAsync(x => x.RefId == vote.RefId && x.Score > 0); + comment.UpVotes = (int) db.Count(x => x.RefId == vote.RefId && x.Score > 0); await questions.SaveMetaAsync(vote.PostId, meta); } } diff --git a/MyApp.ServiceInterface/App/CreateFlagCommand.cs b/MyApp.ServiceInterface/App/CreateFlagCommand.cs index 3d00fab..9906869 100644 --- a/MyApp.ServiceInterface/App/CreateFlagCommand.cs +++ b/MyApp.ServiceInterface/App/CreateFlagCommand.cs @@ -7,10 +7,7 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Database)] [Worker(Databases.App)] -public class CreateFlagCommand(IDbConnection db) : AsyncCommand +public class CreateFlagCommand(IDbConnection db) : SyncCommand { - protected override async Task RunAsync(Flag request, CancellationToken token) - { - await db.InsertAsync(request, token: token); - } + protected override void Run(Flag request) => db.Insert(request); } diff --git a/MyApp.ServiceInterface/App/CreateNotificationCommand.cs b/MyApp.ServiceInterface/App/CreateNotificationCommand.cs index 0124564..a8eee7e 100644 --- a/MyApp.ServiceInterface/App/CreateNotificationCommand.cs +++ b/MyApp.ServiceInterface/App/CreateNotificationCommand.cs @@ -8,11 +8,11 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Notifications)] [Worker(Databases.App)] -public class CreateNotificationCommand(AppConfig appConfig, IDbConnection db) : AsyncCommand +public class CreateNotificationCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - protected override async Task RunAsync(Notification request, CancellationToken token) + protected override void Run(Notification request) { - await db.InsertAsync(request, token: token); + db.Insert(request); appConfig.IncrUnreadNotificationsFor(request.UserName); } } diff --git a/MyApp.ServiceInterface/App/CreatePostCommand.cs b/MyApp.ServiceInterface/App/CreatePostCommand.cs index 4f64849..204b44b 100644 --- a/MyApp.ServiceInterface/App/CreatePostCommand.cs +++ b/MyApp.ServiceInterface/App/CreatePostCommand.cs @@ -20,22 +20,22 @@ protected override async Task RunAsync(Post post, CancellationToken token) if (post.Id > 0) { - await db.InsertAsync(post, token: token); + db.Insert(post); } else { - post.Id = (int)await db.InsertAsync(post, selectIdentity: true, token: token); + post.Id = (int)db.Insert(post, selectIdentity: true); } var createdBy = post.CreatedBy; if (createdBy != null && post.PostTypeId == 1) { - await appConfig.ResetUserQuestionsAsync(db, createdBy); + appConfig.ResetUserQuestions(db, createdBy); } try { - await db.InsertAsync(new StatTotals + db.Insert(new StatTotals { Id = $"{post.Id}", PostId = post.Id, @@ -43,17 +43,17 @@ await db.InsertAsync(new StatTotals DownVotes = 0, StartingUpVotes = 0, CreatedBy = post.CreatedBy, - }, token: token); + }); } catch (Exception e) { log.LogWarning("Couldn't insert StatTotals for Post {PostId}: '{Message}', updating instead...", post.Id, e.Message); - await db.UpdateOnlyAsync(() => new StatTotals + db.UpdateOnly(() => new StatTotals { PostId = post.Id, CreatedBy = post.CreatedBy, - }, x => x.Id == $"{post.Id}", token: token); + }, x => x.Id == $"{post.Id}"); } if (!string.IsNullOrEmpty(body)) @@ -63,8 +63,8 @@ await db.InsertAsync(new StatTotals .Where(x => x != createdBy && appConfig.IsHuman(x)).ToList(); if (userNameMentions.Count > 0) { - var existingUsers = await db.SelectAsync(db.From() - .Where(x => userNameMentions.Contains(x.UserName!)), token: token); + var existingUsers = db.Select(db.From() + .Where(x => userNameMentions.Contains(x.UserName!))); foreach (var existingUser in existingUsers) { @@ -74,7 +74,7 @@ await db.InsertAsync(new StatTotals var startPos = Math.Max(0, firstMentionPos - 50); if (appConfig.IsHuman(existingUser.UserName)) { - await db.InsertAsync(new Notification + db.Insert(new Notification { UserName = existingUser.UserName!, Type = NotificationType.QuestionMention, @@ -83,7 +83,7 @@ await db.InsertAsync(new Notification CreatedDate = post.CreationDate, Summary = cleanBody.GenerateNotificationSummary(startPos), RefUserName = createdBy, - }, token: token); + }); appConfig.IncrUnreadNotificationsFor(existingUser.UserName!); } } @@ -92,7 +92,7 @@ await db.InsertAsync(new Notification if (appConfig.IsHuman(post.CreatedBy)) { - await db.InsertAsync(new Achievement + db.Insert(new Achievement { UserName = post.CreatedBy!, Type = AchievementType.NewQuestion, @@ -100,18 +100,18 @@ await db.InsertAsync(new Achievement PostId = post.Id, Score = 1, CreatedDate = DateTime.UtcNow, - }, token: token); + }); appConfig.IncrUnreadAchievementsFor(post.CreatedBy!); // Setup auto-watch for new questions (Sending Emails for new Answers) - await db.InsertAsync(new WatchPost + db.Insert(new WatchPost { UserName = post.CreatedBy!, PostId = post.Id, CreatedDate = post.CreationDate, // Email new answers 1hr after asking question AfterDate = DateTime.UtcNow.Add(TimeSpan.FromHours(1)), - }, token: token); + }); } } } diff --git a/MyApp.ServiceInterface/App/CreatePostVoteCommand.cs b/MyApp.ServiceInterface/App/CreatePostVoteCommand.cs index 7b6e477..05f08bb 100644 --- a/MyApp.ServiceInterface/App/CreatePostVoteCommand.cs +++ b/MyApp.ServiceInterface/App/CreatePostVoteCommand.cs @@ -11,9 +11,9 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] [Tag(Tags.Database)] public class CreatePostVoteCommand(AppConfig appConfig, IDbConnection db, IBackgroundJobs jobs) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(Vote vote, CancellationToken token) + protected override void Run(Vote vote) { if (string.IsNullOrEmpty(vote.RefId)) throw new ArgumentNullException(nameof(vote.RefId)); @@ -24,22 +24,22 @@ protected override async Task RunAsync(Vote vote, CancellationToken token) var voteUp = isAnswer ? AchievementType.AnswerUpVote : AchievementType.QuestionUpVote; var voteDown = isAnswer ? AchievementType.AnswerDownVote : AchievementType.QuestionDownVote; - var rowsDeleted = await db.DeleteAsync(new { vote.RefId, vote.UserName }, token: token); + var rowsDeleted = db.Delete(new { vote.RefId, vote.UserName }); if (rowsDeleted > 0 && vote.RefUserName != null) { // If they rescinded their previous vote, also remove the Ref User's previous achievement for that Q or A - await db.ExecuteNonQueryAsync( + db.ExecuteNonQuery( "DELETE FROM Achievement WHERE UserName = @TargetUser AND RefUserName = @VoterUserName AND RefId = @RefId AND Type IN (@voteUp,@voteDown)", - new { TargetUser = vote.RefUserName, VoterUserName = vote.UserName , vote.RefId, voteUp, voteDown }, token: token); + new { TargetUser = vote.RefUserName, VoterUserName = vote.UserName , vote.RefId, voteUp, voteDown }); } if (vote.Score != 0) { - await db.InsertAsync(vote, token: token); + db.Insert(vote); if (appConfig.IsHuman(vote.RefUserName)) { - await db.InsertAsync(new Achievement + db.Insert(new Achievement { UserName = vote.RefUserName!, // User who's Q or A was voted on RefUserName = vote.UserName, // User who voted @@ -48,7 +48,7 @@ await db.InsertAsync(new Achievement Type = vote.Score > 0 ? voteUp : voteDown, Score = vote.Score > 0 ? 10 : -1, // 10 points for UpVote, -1 point for DownVote CreatedDate = DateTime.UtcNow, - }, token: token); + }); appConfig.IncrUnreadAchievementsFor(vote.RefUserName!); } } diff --git a/MyApp.ServiceInterface/App/DeleteAnswersCommand.cs b/MyApp.ServiceInterface/App/DeleteAnswersCommand.cs index b9fcf28..3319840 100644 --- a/MyApp.ServiceInterface/App/DeleteAnswersCommand.cs +++ b/MyApp.ServiceInterface/App/DeleteAnswersCommand.cs @@ -8,17 +8,17 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] [Tag(Tags.Answers)] -public class DeleteAnswersCommand(IDbConnection db) : AsyncCommand +public class DeleteAnswersCommand(IDbConnection db) : SyncCommand { - protected override async Task RunAsync(DeleteAnswers request, CancellationToken token) + protected override void Run(DeleteAnswers request) { foreach (var refId in request.Ids) { - await db.DeleteAsync(x => x.RefId == refId, token: token); - await db.DeleteByIdAsync(refId, token: token); - await db.DeleteAsync(x => x.Id == refId, token: token); - await db.DeleteAsync(x => x.RefId == refId, token: token); - await db.DeleteAsync(x => x.RefId == refId, token: token); + db.Delete(x => x.RefId == refId); + db.DeleteById(refId); + db.Delete(x => x.Id == refId); + db.Delete(x => x.RefId == refId); + db.Delete(x => x.RefId == refId); } } } diff --git a/MyApp.ServiceInterface/App/DeleteCommentCommand.cs b/MyApp.ServiceInterface/App/DeleteCommentCommand.cs index 6bfd556..37823ee 100644 --- a/MyApp.ServiceInterface/App/DeleteCommentCommand.cs +++ b/MyApp.ServiceInterface/App/DeleteCommentCommand.cs @@ -8,13 +8,13 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Database)] [Worker(Databases.App)] -public class DeleteCommentCommand(AppConfig appConfig, IDbConnection db) : AsyncCommand +public class DeleteCommentCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - protected override async Task RunAsync(DeleteComment request, CancellationToken token) + protected override void Run(DeleteComment request) { var refId = $"{request.Id}-{request.Created}"; - var rowsAffected = await db.DeleteAsync(db.From() - .Where(x => x.RefId == refId && x.RefUserName == request.CreatedBy), token: token); + var rowsAffected = db.Delete(db.From() + .Where(x => x.RefId == refId && x.RefUserName == request.CreatedBy)); if (rowsAffected > 0) { appConfig.ResetUsersUnreadNotifications(db); diff --git a/MyApp.ServiceInterface/App/DeletePostsCommand.cs b/MyApp.ServiceInterface/App/DeletePostsCommand.cs index 0b7323a..e288a12 100644 --- a/MyApp.ServiceInterface/App/DeletePostsCommand.cs +++ b/MyApp.ServiceInterface/App/DeletePostsCommand.cs @@ -9,18 +9,18 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] [Tag(Tags.Database)] public class DeletePostsCommand(AppConfig appConfig, IDbConnection db) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(DeletePosts request, CancellationToken token) + protected override void Run(DeletePosts request) { foreach (var postId in request.Ids) { - await db.DeleteAsync(x => x.PostId == postId, token: token); - await db.DeleteByIdAsync(postId, token: token); - await db.DeleteAsync(x => x.PostId == postId, token: token); - await db.DeleteAsync(x => x.PostId == postId, token: token); - await db.DeleteAsync(x => x.PostId == postId, token: token); - await db.DeleteAsync(x => x.PostId == postId, token: token); + db.Delete(x => x.PostId == postId); + db.DeleteById(postId); + db.Delete(x => x.PostId == postId); + db.Delete(x => x.PostId == postId); + db.Delete(x => x.PostId == postId); + db.Delete(x => x.PostId == postId); appConfig.ResetInitialPostId(db); } } diff --git a/MyApp.ServiceInterface/App/MarkAsReadCommand.cs b/MyApp.ServiceInterface/App/MarkAsReadCommand.cs index 690f9d2..2533372 100644 --- a/MyApp.ServiceInterface/App/MarkAsReadCommand.cs +++ b/MyApp.ServiceInterface/App/MarkAsReadCommand.cs @@ -6,37 +6,37 @@ namespace MyApp.ServiceInterface.App; -[Worker(Databases.App)] [Tag(Tags.Notifications)] -public class MarkAsReadCommand(AppConfig appConfig, IDbConnection db) : AsyncCommand +[Worker(Databases.App)] +public class MarkAsReadCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - protected override async Task RunAsync(MarkAsRead request, CancellationToken token) + protected override void Run(MarkAsRead request) { var userName = request.UserName; if (request.AllNotifications == true) { - await db.UpdateOnlyAsync(() => new Notification { Read = true }, x => x.UserName == userName, token: token); + db.UpdateOnly(() => new Notification { Read = true }, x => x.UserName == userName); appConfig.UsersUnreadNotifications[userName] = 0; } else if (request.NotificationIds?.Count > 0) { - await db.UpdateOnlyAsync(() => new Notification { Read = true }, - x => x.UserName == userName && request.NotificationIds.Contains(x.Id), token: token); - appConfig.UsersUnreadNotifications[userName] = (int) await db.CountAsync( - db.From().Where(x => x.UserName == userName && !x.Read), token: token); + db.UpdateOnly(() => new Notification { Read = true }, + x => x.UserName == userName && request.NotificationIds.Contains(x.Id)); + appConfig.UsersUnreadNotifications[userName] = (int) db.Count( + db.From().Where(x => x.UserName == userName && !x.Read)); } // Mark all achievements as read isn't used, they're auto reset after viewed if (request.AllAchievements == true) { - await db.UpdateOnlyAsync(() => new Achievement { Read = true }, x => x.UserName == userName, token: token); + db.UpdateOnly(() => new Achievement { Read = true }, x => x.UserName == userName); appConfig.UsersUnreadAchievements[userName] = 0; } else if (request.AchievementIds?.Count > 0) { - await db.UpdateOnlyAsync(() => new Achievement { Read = true }, - x => x.UserName == userName && request.AchievementIds.Contains(x.Id), token: token); - appConfig.UsersUnreadAchievements[userName] = (int) await db.CountAsync( - db.From().Where(x => x.UserName == userName && !x.Read), token: token); + db.UpdateOnly(() => new Achievement { Read = true }, + x => x.UserName == userName && request.AchievementIds.Contains(x.Id)); + appConfig.UsersUnreadAchievements[userName] = (int) db.Count( + db.From().Where(x => x.UserName == userName && !x.Read)); } } } diff --git a/MyApp.ServiceInterface/App/MarkPostAsReadCommand.cs b/MyApp.ServiceInterface/App/MarkPostAsReadCommand.cs index 70cc2b0..60db359 100644 --- a/MyApp.ServiceInterface/App/MarkPostAsReadCommand.cs +++ b/MyApp.ServiceInterface/App/MarkPostAsReadCommand.cs @@ -8,12 +8,12 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] [Tag(Tags.Notifications)] -public class MarkPostAsReadCommand(AppConfig appConfig, IDbConnection db, QuestionsProvider questions) : AsyncCommand +public class MarkPostAsReadCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - protected override async Task RunAsync(MarkPostAsRead request, CancellationToken token) + protected override void Run(MarkPostAsRead request) { - await db.UpdateOnlyAsync(() => new Notification { Read = true }, - where:x => x.UserName == request.UserName && x.PostId == request.PostId, token:token); - await appConfig.ResetUnreadNotificationsForAsync(db, request.UserName); + db.UpdateOnly(() => new Notification { Read = true }, + where:x => x.UserName == request.UserName && x.PostId == request.PostId); + appConfig.ResetUnreadNotificationsFor(db, request.UserName); } } diff --git a/MyApp.ServiceInterface/App/NewCommentCommand.cs b/MyApp.ServiceInterface/App/NewCommentCommand.cs index 4408376..ae92ddf 100644 --- a/MyApp.ServiceInterface/App/NewCommentCommand.cs +++ b/MyApp.ServiceInterface/App/NewCommentCommand.cs @@ -16,18 +16,18 @@ public class NewComment [Tag(Tags.Database)] [Worker(Databases.App)] -public class NewCommentCommand(AppConfig appConfig, IDbConnection db) : AsyncCommand +public class NewCommentCommand(AppConfig appConfig, IDbConnection db) : SyncCommand { - protected override async Task RunAsync(NewComment request, CancellationToken token) + protected override void Run(NewComment request) { var refId = request.RefId; var postId = refId.LeftPart('-').ToInt(); - var post = await db.SingleByIdAsync(postId, token: token); + var post = db.SingleById(postId); if (post != null) { var isAnswer = refId.IndexOf('-') > 0; var createdBy = isAnswer - ? (await db.SingleByIdAsync(refId, token: token))?.CreatedBy + ? db.SingleById(refId)?.CreatedBy : post.CreatedBy; var comment = request.Comment; @@ -37,7 +37,7 @@ protected override async Task RunAsync(NewComment request, CancellationToken tok if (createdBy != null && createdBy != comment.CreatedBy && appConfig.IsHuman(createdBy)) { - await db.InsertAsync(new Notification + db.Insert(new Notification { UserName = createdBy, Type = NotificationType.NewComment, @@ -46,13 +46,13 @@ await db.InsertAsync(new Notification CreatedDate = createdDate, Summary = cleanBody.GenerateNotificationSummary(), RefUserName = comment.CreatedBy, - }, token: token); + }); appConfig.IncrUnreadNotificationsFor(createdBy); } var lastUpdated = request.LastUpdated; appConfig.SetLastUpdated(request.RefId, lastUpdated); - await db.UpdateOnlyAsync(() => new StatTotals + db.UpdateOnly(() => new StatTotals { LastUpdated = lastUpdated, }, where: x => x.Id == request.RefId); @@ -62,7 +62,7 @@ await db.InsertAsync(new Notification .ToList(); if (userNameMentions.Count > 0) { - var existingUsers = await db.SelectAsync(db.From() + var existingUsers = db.Select(db.From() .Where(x => userNameMentions.Contains(x.UserName!))); foreach (var existingUser in existingUsers) @@ -73,7 +73,7 @@ await db.InsertAsync(new Notification var startPos = Math.Max(0, firstMentionPos - 50); if (appConfig.IsHuman(existingUser.UserName)) { - await db.InsertAsync(new Notification + db.Insert(new Notification { UserName = existingUser.UserName!, Type = NotificationType.CommentMention, diff --git a/MyApp.ServiceInterface/App/PostSubscriptionsCommand.cs b/MyApp.ServiceInterface/App/PostSubscriptionsCommand.cs index b1cb873..21d779c 100644 --- a/MyApp.ServiceInterface/App/PostSubscriptionsCommand.cs +++ b/MyApp.ServiceInterface/App/PostSubscriptionsCommand.cs @@ -15,9 +15,9 @@ public class PostSubscriptions [Worker(Databases.App)] [Tag(Tags.Notifications)] -public class PostSubscriptionsCommand(IDbConnection db) : AsyncCommand +public class PostSubscriptionsCommand(IDbConnection db) : SyncCommand { - protected override async Task RunAsync(PostSubscriptions request, CancellationToken token) + protected override void Run(PostSubscriptions request) { var now = DateTime.UtcNow; if (request.Subscriptions is { Count: > 0 }) @@ -29,12 +29,12 @@ protected override async Task RunAsync(PostSubscriptions request, CancellationTo CreatedDate = now, AfterDate = now, }); - await db.InsertAllAsync(subs, token: token); + db.InsertAll(subs); } if (request.Unsubscriptions is { Count: > 0 }) { - await db.DeleteAsync( - x => x.UserName == request.UserName && request.Unsubscriptions.Contains(x.PostId), token: token); + db.Delete( + x => x.UserName == request.UserName && request.Unsubscriptions.Contains(x.PostId)); } } } diff --git a/MyApp.ServiceInterface/App/SaveGradeResultCommand.cs b/MyApp.ServiceInterface/App/SaveGradeResultCommand.cs index 5812fd1..7c71546 100644 --- a/MyApp.ServiceInterface/App/SaveGradeResultCommand.cs +++ b/MyApp.ServiceInterface/App/SaveGradeResultCommand.cs @@ -11,22 +11,22 @@ namespace MyApp.ServiceInterface.App; [Tag(Tags.Answers)] [Worker(Databases.App)] public class SaveGradeResultCommand(AppConfig appConfig, IDbConnection db, WorkerAnswerNotifier answerNotifier, IBackgroundJobs jobs) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(StatTotals request, CancellationToken token) + protected override void Run(StatTotals request) { var lastUpdated = request.LastUpdated ?? DateTime.UtcNow; appConfig.SetLastUpdated(request.Id, lastUpdated); - var updatedRow = await db.UpdateOnlyAsync(() => new StatTotals + var updatedRow = db.UpdateOnly(() => new StatTotals { StartingUpVotes = request.StartingUpVotes, CreatedBy = request.CreatedBy, LastUpdated = lastUpdated, - }, x => x.Id == request.Id, token: token); + }, x => x.Id == request.Id); if (updatedRow == 0) { - await db.InsertAsync(request, token:token); + db.Insert(request); } if (request.CreatedBy != null) diff --git a/MyApp.ServiceInterface/App/SendWatchedTagEmailsCommand.cs b/MyApp.ServiceInterface/App/SendWatchedTagEmailsCommand.cs index 63be7dc..b25d93e 100644 --- a/MyApp.ServiceInterface/App/SendWatchedTagEmailsCommand.cs +++ b/MyApp.ServiceInterface/App/SendWatchedTagEmailsCommand.cs @@ -17,20 +17,20 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] public class SendWatchedTagEmailsCommand(ILogger logger, IBackgroundJobs jobs, IDbConnectionFactory dbFactory, EmailRenderer renderer) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(CancellationToken token) + protected override void Run() { var log = Request.CreateJobLogger(jobs, logger); //var job = Request.GetBackgroundJob(); var yesterday = DateTime.UtcNow.AddDays(-1).Date; var day = yesterday.ToString("yyyy-MM-dd"); - using var db = await dbFactory.OpenDbConnectionAsync(token:token); - if (await db.ExistsAsync(db.From().Where(x => x.Date == day), token:token)) + using var db = dbFactory.Open(); + if (db.Exists(db.From().Where(x => x.Date == day))) return; - var newPosts = await db.SelectAsync(db.From().Where(x => - x.CreationDate >= yesterday && x.CreationDate < yesterday.AddDays(1)), token:token); + var newPosts = db.Select(db.From().Where(x => + x.CreationDate >= yesterday && x.CreationDate < yesterday.AddDays(1))); if (newPosts.Count == 0) { log.LogInformation("No new posts found for {Date}", day); @@ -49,8 +49,8 @@ protected override async Task RunAsync(CancellationToken token) } var uniqueTags = tagGroups.Keys.ToSet(); - var watchTags = await db.SelectAsync(db.From() - .Where(x => uniqueTags.Contains(x.Tag)), token: token); + var watchTags = db.Select(db.From() + .Where(x => uniqueTags.Contains(x.Tag))); if (watchTags.Count == 0) { log.LogInformation("No Tag Watchers found for {Date}", day); @@ -58,10 +58,10 @@ protected override async Task RunAsync(CancellationToken token) } var uniqueUserNames = watchTags.Select(x => x.UserName).ToSet(); - var users = await db.SelectAsync( - x => uniqueUserNames.Contains(x.UserName!), token: token); + var users = db.Select( + x => uniqueUserNames.Contains(x.UserName!)); - using var dbCreatorKit = await dbFactory.OpenDbConnectionAsync(Databases.CreatorKit, token:token); + using var dbCreatorKit = dbFactory.Open(Databases.CreatorKit); var mailRuns = 0; var orderedTags = uniqueTags.OrderBy(x => x).ToList(); @@ -85,7 +85,7 @@ protected override async Task RunAsync(CancellationToken token) PostIds = postIds, CreatedDate = DateTime.UtcNow, }; - watchPostMail.Id = (int)await db.InsertAsync(watchPostMail, selectIdentity: true, token:token); + watchPostMail.Id = (int)db.Insert(watchPostMail, selectIdentity: true); log.LogInformation("Created {Day} WatchPostMail {Id} for {Tag} with posts:{PostIds} for users:{UserNames}", day, watchPostMail.Id, tag, postIds.Join(","), userNames.Join(",")); @@ -99,11 +99,11 @@ protected override async Task RunAsync(CancellationToken token) ["date"] = monthDay, ["posts"] = posts, }; - var html = await new PageResult(context.GetPage("content")) + var html = new PageResult(context.GetPage("content")) { Layout = "layout", Args = args, - }.RenderToStringAsync(); + }.RenderScript(); args.Remove("model"); @@ -118,13 +118,13 @@ protected override async Task RunAsync(CancellationToken token) GeneratorArgs = args, ExternalRef = externalRef, }; - mailRun.Id = (int)await dbCreatorKit.InsertAsync(mailRun, selectIdentity: true, token:token); + mailRun.Id = (int)dbCreatorKit.Insert(mailRun, selectIdentity: true); mailRuns++; - await db.UpdateOnlyAsync(() => new WatchPostMail + db.UpdateOnly(() => new WatchPostMail { MailRunId = mailRun.Id, - }, where: x => x.Id == watchPostMail.Id, token:token); + }, where: x => x.Id == watchPostMail.Id); var emails = 0; foreach (var tagWatcher in tagWatchers) @@ -144,7 +144,7 @@ protected override async Task RunAsync(CancellationToken token) BodyHtml = html, }; - var contact = await dbCreatorKit.GetOrCreateContact(user); + var contact = dbCreatorKit.GetOrCreateContact(user); var mailMessage = new MailMessageRun { @@ -157,20 +157,20 @@ protected override async Task RunAsync(CancellationToken token) CreatedDate = DateTime.UtcNow, ExternalRef = externalRef, }; - mailMessage.Id = (int)await dbCreatorKit.InsertAsync(mailMessage, selectIdentity: true, token:token); + mailMessage.Id = (int)dbCreatorKit.Insert(mailMessage, selectIdentity: true); emails++; } var generatedDate = DateTime.UtcNow; - await db.UpdateOnlyAsync(() => new WatchPostMail + db.UpdateOnly(() => new WatchPostMail { GeneratedDate = generatedDate, - }, where: x => x.Id == watchPostMail.Id, token: token); - await dbCreatorKit.UpdateOnlyAsync(() => new MailRun + }, where: x => x.Id == watchPostMail.Id); + dbCreatorKit.UpdateOnly(() => new MailRun { EmailsCount = emails, GeneratedDate = generatedDate, - }, where: x => x.Id == mailRun.Id, token: token); + }, where: x => x.Id == mailRun.Id); log.LogInformation("Generated {Count} in {Day} MailRun {Id} for {Tag}", emails, day, mailRun.Id, tag); diff --git a/MyApp.ServiceInterface/App/TagSubscriptionsCommand.cs b/MyApp.ServiceInterface/App/TagSubscriptionsCommand.cs index e004c6f..b402023 100644 --- a/MyApp.ServiceInterface/App/TagSubscriptionsCommand.cs +++ b/MyApp.ServiceInterface/App/TagSubscriptionsCommand.cs @@ -14,9 +14,9 @@ public class TagSubscriptions [Worker(Databases.App)] [Tag(Tags.Notifications)] -public class TagSubscriptionsCommand(IDbConnection db) : AsyncCommand +public class TagSubscriptionsCommand(IDbConnection db) : SyncCommand { - protected override async Task RunAsync(TagSubscriptions request, CancellationToken token) + protected override void Run(TagSubscriptions request) { var now = DateTime.UtcNow; if (request.Subscriptions is { Count: > 0 }) @@ -27,12 +27,12 @@ protected override async Task RunAsync(TagSubscriptions request, CancellationTok Tag = x, CreatedDate = now, }); - await db.InsertAllAsync(subs, token: token); + db.InsertAll(subs); } if (request.Unsubscriptions is { Count: > 0 }) { - await db.DeleteAsync( - x => x.UserName == request.UserName && request.Unsubscriptions.Contains(x.Tag), token: token); + db.Delete( + x => x.UserName == request.UserName && request.Unsubscriptions.Contains(x.Tag)); } } } diff --git a/MyApp.ServiceInterface/App/UpdatePostCommand.cs b/MyApp.ServiceInterface/App/UpdatePostCommand.cs index 78050d2..9ba6062 100644 --- a/MyApp.ServiceInterface/App/UpdatePostCommand.cs +++ b/MyApp.ServiceInterface/App/UpdatePostCommand.cs @@ -7,11 +7,12 @@ namespace MyApp.ServiceInterface.App; [Worker(Databases.App)] [Tag(Tags.Questions)] -public class UpdatePostCommand(IDbConnection db) : AsyncCommand +public class UpdatePostCommand(IDbConnection db) : SyncCommand { - protected override async Task RunAsync(Post question, CancellationToken token) + protected override void Run(Post question) { - await db.UpdateOnlyAsync(() => new Post { + db.UpdateOnly(() => new Post + { Title = question.Title, Tags = question.Tags, Slug = question.Slug, @@ -19,6 +20,6 @@ protected override async Task RunAsync(Post question, CancellationToken token) ModifiedBy = question.ModifiedBy, LastActivityDate = question.LastActivityDate, LastEditDate = question.LastEditDate, - }, x => x.Id == question.Id, token: token); + }, x => x.Id == question.Id); } } diff --git a/MyApp.ServiceInterface/CreatorKit/EmailRenderer.cs b/MyApp.ServiceInterface/CreatorKit/EmailRenderer.cs index 6d9247a..8a0c1b5 100644 --- a/MyApp.ServiceInterface/CreatorKit/EmailRenderer.cs +++ b/MyApp.ServiceInterface/CreatorKit/EmailRenderer.cs @@ -34,11 +34,11 @@ public static EmailRenderer Create(IVirtualFiles vfs, IBackgroundJobs jobs) CreatedIds = new() }; - public async Task CreateMessageAsync(IDbConnection db, MailMessage msg) + public MailMessage CreateMessage(IDbConnection db, MailMessage msg) { msg.CreatedDate = DateTime.UtcNow; msg.ExternalRef ??= CreateRef(); - msg.Id = (int) await db.InsertAsync(msg, selectIdentity:true); + msg.Id = (int) db.Insert(msg, selectIdentity:true); if (!msg.Draft) { SendMailMessage(msg.Id); @@ -47,25 +47,25 @@ public async Task CreateMessageAsync(IDbConnection db, MailMessage return msg; } - public async Task CreateMailRunAsync(IDbConnection db, MailRun mailRun, object request) + public MailRun CreateMailRun(IDbConnection db, MailRun mailRun, object request) { if (request is MailRunBase { MailingList: MailingList.None }) throw new ArgumentNullException(nameof(MailRunBase.MailingList)); mailRun.CreatedDate = DateTime.UtcNow; mailRun.ExternalRef ??= CreateRef(); - mailRun.Id = (int) await db.InsertAsync(mailRun.FromRequest(request), selectIdentity:true); + mailRun.Id = (int) db.Insert(mailRun.FromRequest(request), selectIdentity:true); return mailRun; } - public async Task CreateMessageRunAsync(IDbConnection db, MailMessageRun msg, + public MailMessageRun CreateMessageRun(IDbConnection db, MailMessageRun msg, MailRun mailRun, Contact sub) { msg.ExternalRef ??= CreateRef(); msg.CreatedDate = DateTime.UtcNow; msg.MailRunId = mailRun.Id; msg.ContactId = sub.Id; - msg.Id = (int) await db.InsertAsync(msg, selectIdentity:true); + msg.Id = (int) db.Insert(msg, selectIdentity:true); return msg; } @@ -98,8 +98,8 @@ public async Task RenderToHtmlAsync(IDbConnection db, ScriptContext cont if (requiresPopulating) { var sub = email.Email != null - ? await db.SingleAsync(x => x.EmailLower == email.Email.ToLower()) - : await db.SingleAsync(x => x.ExternalRef == email.ExternalRef); + ? db.Single(x => x.EmailLower == email.Email.ToLower()) + : db.Single(x => x.ExternalRef == email.ExternalRef); if (sub == null) throw HttpError.NotFound("Contact was not found"); request.PopulateWith(sub); @@ -230,25 +230,25 @@ public enum MailingList public static class EmailRendererUtils { - public static async Task CompletedMailRunAsync(this IDbConnection db, MailRun mailRun, MailRunResponse ret) + public static void CompletedMailRun(this IDbConnection db, MailRun mailRun, MailRunResponse ret) { ret.Id = mailRun.Id; ret.TimeTaken = DateTime.UtcNow - ret.StartedAt; - await db.UpdateMailRunGeneratedEmailsAsync(mailRun.Id, ret.CreatedIds.Count); + db.UpdateMailRunGeneratedEmails(mailRun.Id, ret.CreatedIds.Count); } - public static async Task UpdateMailRunGeneratedEmailsAsync(this IDbConnection db, int mailRunId, int generatedEmails) + public static void UpdateMailRunGeneratedEmails(this IDbConnection db, int mailRunId, int generatedEmails) { - await db.UpdateOnlyAsync(() => new MailRun { GeneratedDate = DateTime.UtcNow, EmailsCount = generatedEmails }, + db.UpdateOnly(() => new MailRun { GeneratedDate = DateTime.UtcNow, EmailsCount = generatedEmails }, where: x => x.Id == mailRunId); } - public static async Task> GetActiveSubscribersAsync(this IDbConnection db, MailingList mailingList) + public static List GetActiveSubscribers(this IDbConnection db, MailingList mailingList) { if (mailingList == MailingList.None) throw new ArgumentNullException(nameof(mailingList)); - return await db.SelectAsync(db.From(db.TableAlias("c")) + return db.Select(db.From(db.TableAlias("c")) .Where(x => x.DeletedDate == null && x.UnsubscribedDate == null && x.VerifiedDate != null && (mailingList & x.MailingLists) == mailingList) .WhereNotExists(db.From() diff --git a/MyApp.ServiceInterface/CreatorKit/EmailRenderersServices.cs b/MyApp.ServiceInterface/CreatorKit/EmailRenderersServices.cs index 7af3d60..0f6b426 100644 --- a/MyApp.ServiceInterface/CreatorKit/EmailRenderersServices.cs +++ b/MyApp.ServiceInterface/CreatorKit/EmailRenderersServices.cs @@ -70,7 +70,7 @@ public async Task Any(RenderTagQuestionsEmail request) { var context = renderer.CreateMailContext(layout:"tags", page:"tagged-questions"); - var posts = await Db.SelectAsync(Db.From() + var posts = Db.Select(Db.From() .Where(x => x.CreationDate >= request.Date && x.CreationDate < request.Date.AddDays(1)) .Where("replace(replace(tags,'[',','),']',',') LIKE '%,' || {0} || ',%'", request.Tag) .Limit(10)); diff --git a/MyApp.ServiceInterface/CreatorKit/EmailServices.cs b/MyApp.ServiceInterface/CreatorKit/EmailServices.cs index 25d4334..778f6b5 100644 --- a/MyApp.ServiceInterface/CreatorKit/EmailServices.cs +++ b/MyApp.ServiceInterface/CreatorKit/EmailServices.cs @@ -13,7 +13,7 @@ public class EmailServices(EmailRenderer renderer) : Service public async Task Any(UpdateMailMessageDraft request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var message = await db.SingleByIdAsync(request.Id); + var message = db.SingleById(request.Id); var renderRequestType = HostContext.Metadata.GetRequestType(message.Renderer); message.Layout = request.Layout; message.Template = request.Template; @@ -36,7 +36,7 @@ public async Task Any(UpdateMailMessageDraft request) else message.Message.BodyHtml = responseBody; - await db.UpdateAsync(message); + db.Update(message); if (request.Send == true) { @@ -49,11 +49,11 @@ public async Task Any(UpdateMailMessageDraft request) public async Task Any(SimpleTextEmail request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var contact = await db.GetOrCreateContact(request); + var contact = db.GetOrCreateContact(request); var viewRequest = request.ConvertTo().FromContact(contact); var bodyText = (string)await Gateway.SendAsync(typeof(string), viewRequest); - var email = await renderer.CreateMessageAsync(db, new MailMessage + var email = renderer.CreateMessage(db, new MailMessage { Draft = request.Draft ?? false, Message = new EmailMessage @@ -70,11 +70,11 @@ public async Task Any(SimpleTextEmail request) public async Task Any(CustomHtmlEmail request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var contact = await db.GetOrCreateContact(request); + var contact = db.GetOrCreateContact(request); var viewRequest = request.ConvertTo().FromContact(contact); var bodyHtml = (string)await Gateway.SendAsync(typeof(string), viewRequest); - var email = await renderer.CreateMessageAsync(db, new MailMessage + var email = renderer.CreateMessage(db, new MailMessage { Draft = request.Draft ?? false, Message = new EmailMessage @@ -91,11 +91,11 @@ public async Task Any(CustomHtmlEmail request) public async Task Any(TagQuestionsEmail request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var contact = await db.GetOrCreateContact(request); + var contact = db.GetOrCreateContact(request); var viewRequest = request.ConvertTo().FromContact(contact); var bodyHtml = (string)await Gateway.SendAsync(typeof(string), viewRequest); - var email = await renderer.CreateMessageAsync(db, new MailMessage + var email = renderer.CreateMessage(db, new MailMessage { Draft = request.Draft ?? false, Message = new EmailMessage diff --git a/MyApp.ServiceInterface/CreatorKit/MailingServices.cs b/MyApp.ServiceInterface/CreatorKit/MailingServices.cs index 021cc24..2a4edab 100644 --- a/MyApp.ServiceInterface/CreatorKit/MailingServices.cs +++ b/MyApp.ServiceInterface/CreatorKit/MailingServices.cs @@ -24,7 +24,7 @@ public async Task Any(CreateContact request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); var mailingList = EnumUtils.FromEnumFlagsList(request.MailingLists); - var contact = await db.SingleAsync(x => x.EmailLower == request.Email.ToLower()); + var contact = db.Single(x => x.EmailLower == request.Email.ToLower()); if (contact != null) { contact.FirstName = request.FirstName; @@ -32,12 +32,12 @@ public async Task Any(CreateContact request) contact.MailingLists |= mailingList; contact.UnsubscribedDate = null; contact.DeletedDate = null; - await db.UpdateAsync(contact); + db.Update(contact); } else { var emailLower = request.Email.ToLower(); - var invalidEmail = await db.SingleAsync(x => x.EmailLower == emailLower); + var invalidEmail = db.Single(x => x.EmailLower == emailLower); if (invalidEmail != null) throw new Exception($"Email is blacklisted as {invalidEmail.Status}"); @@ -53,12 +53,12 @@ public async Task Any(CreateContact request) ExternalRef = renderer.CreateRef(), CreatedDate = DateTime.UtcNow, }; - contact.Id = (int) await db.InsertAsync(contact, selectIdentity: true); + contact.Id = (int) db.Insert(contact, selectIdentity: true); var viewRequest = new RenderCustomHtml { Layout = "marketing", Template = "verify-email" }.FromContact(contact); var context = renderer.CreateMailContext(layout:viewRequest.Layout, page:viewRequest.Template); var bodyHtml = await renderer.RenderToHtmlAsync(db, context, contact); - await renderer.CreateMessageAsync(db, new MailMessage { + renderer.CreateMessage(db, new MailMessage { Message = new EmailMessage { To = contact.ToMailTos(), @@ -74,11 +74,11 @@ public async Task Any(CreateContact request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); var mailingList = EnumUtils.FromEnumFlagsList(request.MailingLists); - var contact = await db.SingleAsync(x => x.EmailLower == request.Email.ToLower()); + var contact = db.Single(x => x.EmailLower == request.Email.ToLower()); if (contact == null) { var emailLower = request.Email.ToLower(); - var invalidEmail = await db.SingleAsync(x => x.EmailLower == emailLower); + var invalidEmail = db.Single(x => x.EmailLower == emailLower); if (invalidEmail != null) throw new Exception($"Email is blacklisted as {invalidEmail.Status}"); @@ -95,7 +95,7 @@ public async Task Any(CreateContact request) CreatedDate = DateTime.UtcNow, VerifiedDate = request.VerifiedDate, }; - contact.Id = (int) await db.InsertAsync(contact, selectIdentity: true); + contact.Id = (int) db.Insert(contact, selectIdentity: true); } return contact; } @@ -104,18 +104,18 @@ public async Task Any(UpdateContactMailingLists request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); var mailingLists = EnumUtils.FromEnumFlagsList(request.MailingLists); - var existing = await db.SingleAsync(x => x.ExternalRef == request.Ref); + var existing = db.Single(x => x.ExternalRef == request.Ref); if (existing == null) throw HttpError.NotFound("Mail subscription not found"); if (request.UnsubscribeAll == true) { - await db.UpdateOnlyAsync(() => new Contact { MailingLists = MailingList.None, UnsubscribedDate = DateTime.UtcNow }, + db.UpdateOnly(() => new Contact { MailingLists = MailingList.None, UnsubscribedDate = DateTime.UtcNow }, where: x => x.Id == existing.Id); } else { - await db.UpdateOnlyAsync(() => new Contact { MailingLists = mailingLists, UnsubscribedDate = null, DeletedDate = null }, + db.UpdateOnly(() => new Contact { MailingLists = mailingLists, UnsubscribedDate = null, DeletedDate = null }, where: x => x.Id == existing.Id); } } @@ -124,9 +124,9 @@ public async Task Any(FindContact request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); var contact = request.Ref != null - ? await db.SingleAsync(x => x.ExternalRef == request.Ref) + ? db.Single(x => x.ExternalRef == request.Ref) : request.Email != null - ? await db.SingleAsync(x => x.Email == request.Email) + ? db.Single(x => x.Email == request.Email) : throw HttpError.NotFound("Contact does not exist"); return new FindContactResponse @@ -138,7 +138,7 @@ public async Task Any(FindContact request) public async Task Any(ViewMailMessage request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var msg = await db.SingleByIdAsync(request.Id); + var msg = db.SingleById(request.Id); return new HttpResult(msg.Message.BodyHtml) { ContentType = MimeTypes.Html }; @@ -147,12 +147,12 @@ public async Task Any(ViewMailMessage request) public async Task Any(SendMailMessage request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var msg = await db.SingleByIdAsync(request.Id); + var msg = db.SingleById(request.Id); if (msg.CompletedDate != null && request.Force != true) throw new Exception($"Message {request.Id} has already been sent"); // ensure message is only sent once - if (await db.UpdateOnlyAsync(() => new MailMessage { StartedDate = DateTime.UtcNow, Draft = false }, + if (db.UpdateOnly(() => new MailMessage { StartedDate = DateTime.UtcNow, Draft = false }, where: x => x.Id == request.Id && (x.StartedDate == null || request.Force == true)) == 1) { try @@ -162,12 +162,12 @@ public async Task Any(SendMailMessage request) catch (Exception e) { var error = e.ToResponseStatus(); - await db.UpdateOnlyAsync(() => new MailMessage { Error = error }, + db.UpdateOnly(() => new MailMessage { Error = error }, where: x => x.Id == request.Id); throw; } - await db.UpdateOnlyAsync(() => new MailMessage { CompletedDate = DateTime.UtcNow }, + db.UpdateOnly(() => new MailMessage { CompletedDate = DateTime.UtcNow }, where: x => x.Id == request.Id); } @@ -177,12 +177,12 @@ public async Task Any(SendMailMessage request) public async Task Any(SendMailMessageRun request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var msg = await db.SingleByIdAsync(request.Id); + var msg = db.SingleById(request.Id); if (msg.CompletedDate != null && request.Force != true) throw new Exception($"Message {request.Id} has already been sent"); // ensure message is only sent once - if (await db.UpdateOnlyAsync(() => new MailMessageRun { StartedDate = DateTime.UtcNow }, + if (db.UpdateOnly(() => new MailMessageRun { StartedDate = DateTime.UtcNow }, where: x => x.Id == request.Id && x.StartedDate == null) == 1) { try @@ -192,12 +192,12 @@ public async Task Any(SendMailMessageRun request) catch (Exception e) { var error = e.ToResponseStatus(); - await db.UpdateOnlyAsync(() => new MailMessageRun { Error = error }, + db.UpdateOnly(() => new MailMessageRun { Error = error }, where: x => x.Id == request.Id); throw; } - await db.UpdateOnlyAsync(() => new MailMessageRun { CompletedDate = DateTime.UtcNow }, + db.UpdateOnly(() => new MailMessageRun { CompletedDate = DateTime.UtcNow }, where: x => x.Id == request.Id); } @@ -207,7 +207,7 @@ public async Task Any(SendMailMessageRun request) public async Task Any(ViewMailRunMessage request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var msg = await db.SingleByIdAsync(request.Id); + var msg = db.SingleById(request.Id); return new HttpResult(msg.Message.BodyHtml) { ContentType = MimeTypes.Html }; @@ -216,16 +216,16 @@ public async Task Any(ViewMailRunMessage request) public async Task Any(VerifyEmailAddress request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var rowsAffected = await db.UpdateOnlyAsync(() => new Contact { VerifiedDate = DateTime.UtcNow }, + var rowsAffected = db.UpdateOnly(() => new Contact { VerifiedDate = DateTime.UtcNow }, where: x => x.ExternalRef == request.ExternalRef); - var sub = await db.SingleAsync(x => x.ExternalRef == request.ExternalRef); + var sub = db.Single(x => x.ExternalRef == request.ExternalRef); if (sub != null) { var viewRequest = new RenderCustomHtml { Layout = "marketing", Template = "newsletter-welcome" }.FromContact(sub); var context = renderer.CreateMailContext(layout:viewRequest.Layout, page:viewRequest.Template); var bodyHtml = await renderer.RenderToHtmlAsync(db, context, sub); - await renderer.CreateMessageAsync(db, new MailMessage { + renderer.CreateMessage(db, new MailMessage { Message = new EmailMessage { To = sub.ToMailTos(), Subject = $"{sub.FirstName}, welcome to {AppData.Info.Company}!", @@ -240,13 +240,13 @@ public async Task Any(VerifyEmailAddress request) public async Task Any(SendMailRun request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var msgIdsToSend = await db.ColumnAsync(db.From() + var msgIdsToSend = db.Column(db.From() .Where(x => x.MailRunId == request.Id && (x.CompletedDate == null && x.StartedDate == null)) .Select(x => x.Id)); if (msgIdsToSend.Count > 0) { - await db.UpdateOnlyAsync(() => new MailRun { SentDate = DateTime.UtcNow }, + db.UpdateOnly(() => new MailRun { SentDate = DateTime.UtcNow }, where:x => x.Id == request.Id && x.SentDate == null); } @@ -255,10 +255,10 @@ public async Task Any(SendMailRun request) }); } - public async Task Any(ViewMailRunInfo request) + public object Any(ViewMailRunInfo request) { using var db = HostContext.AppHost.GetDbConnection(Databases.CreatorKit); - var results = await db.SingleAsync<(int, int)>(db.From() + var results = db.Single<(int, int)>(db.From() .Where(x => x.MailRunId == request.Id) .Select(x => new { Completed = Sql.Count(nameof(MailMessageRun.CompletedDate)), @@ -302,12 +302,12 @@ public async Task Any(ViewAppStats request) var totalSql = tables .Map(x => $"SELECT '{x.Item1}' AS Name, (SELECT COUNT(*) FROM {x.Item2}) AS Total") .Join(" UNION "); - var totals = await db.DictionaryAsync(totalSql); + var totals = db.Dictionary(totalSql); var last30DayTotalSql = tables .Map(x => $"SELECT '{x.Item1}' AS Name, (SELECT COUNT(*) FROM {x.Item2} WHERE CreatedDate < @period) AS Total") .Join(" UNION "); - var before30DayTotals = await db.DictionaryAsync(last30DayTotalSql, + var before30DayTotals = db.Dictionary(last30DayTotalSql, new { period = DateTime.UtcNow.AddDays(-30) }); var last30DayTotals = new Dictionary(); @@ -326,7 +326,7 @@ public async Task Any(ViewAppStats request) .Map(x => $"SELECT '{x.Item1}' AS Name, (SELECT COUNT(*) FROM {x.Item2}) AS Total") .Join(" UNION "); using var dbArchive = HostContext.AppHost.GetDbConnection(Databases.Archive); - var archivedTotals = await dbArchive.DictionaryAsync(archivedTotalSql); + var archivedTotals = dbArchive.Dictionary(archivedTotalSql); return new ViewAppStatsResponse { @@ -347,45 +347,45 @@ public async Task Any(ArchiveMail request) var createdBefore = DateTime.UtcNow.AddDays(request.OlderThanDays!.Value * -1); if (request.Messages == true) { - var messages = await db.SelectAsync(x => x.CompletedDate != null && x.CreatedDate < createdBefore); + var messages = db.Select(x => x.CompletedDate != null && x.CreatedDate < createdBefore); try { using var dbArchive = HostContext.AppHost.GetDbConnection(Databases.Archive); foreach (var message in messages) { var archiveMessage = message.ConvertTo(); - await dbArchive.InsertAsync(archiveMessage); + dbArchive.Insert(archiveMessage); messageIdsToDelete.Add(message.Id); } } finally { - await db.DeleteByIdsAsync(messageIdsToDelete); + db.DeleteByIds(messageIdsToDelete); } } if (request.MailRuns == true) { - var mailRuns = await db.SelectAsync(x =>x.CompletedDate != null && x.CreatedDate < createdBefore); + var mailRuns = db.Select(x =>x.CompletedDate != null && x.CreatedDate < createdBefore); try { using var dbArchive = HostContext.AppHost.GetDbConnection(Databases.Archive); foreach (var mailRun in mailRuns) { var archiveMailRun = mailRun.ConvertTo(); - var archiveId = (int) await dbArchive.InsertAsync(archiveMailRun, selectIdentity:true); - var mailRunMessages = await db.SelectAsync(x => x.MailRunId == mailRun.Id); + var archiveId = (int) dbArchive.Insert(archiveMailRun, selectIdentity:true); + var mailRunMessages = db.Select(x => x.MailRunId == mailRun.Id); foreach (var message in mailRunMessages) { var archiveMessage = message.ConvertTo(); archiveMessage.MailRunId = archiveId; - await dbArchive.InsertAsync(archiveMessage); + dbArchive.Insert(archiveMessage); } mailRunIdsToDelete.Add(mailRun.Id); } } finally { - await db.DeleteByIdsAsync(mailRunIdsToDelete); + db.DeleteByIds(mailRunIdsToDelete); } } @@ -400,15 +400,15 @@ public async Task Any(ArchiveMail request) public static class MailMessageExtensions { - public static async Task GetContactByEmail(this IDbConnection db, string email) + public static Contact GetContactByEmail(this IDbConnection db, string email) { - var contact = await db.SingleAsync(x => x.EmailLower == email.ToLower()); + var contact = db.Single(x => x.EmailLower == email.ToLower()); if (contact == null) throw HttpError.NotFound("Contact not found"); return contact; } - public static async Task GetOrCreateContact(this IDbConnection db, ApplicationUser user) + public static Contact GetOrCreateContact(this IDbConnection db, ApplicationUser user) { var email = user.Email ?? throw new ArgumentNullException(nameof(user.Email)); var displayName = user.DisplayName ?? throw new ArgumentNullException(nameof(user.DisplayName)); @@ -417,7 +417,7 @@ public static async Task GetOrCreateContact(this IDbConnection db, Appl ? displayName.LastRightPart(' ') : null; - var sub = await db.SingleAsync(x => x.EmailLower == email.ToLower()); + var sub = db.Single(x => x.EmailLower == email.ToLower()); if (sub == null) { sub = new Contact @@ -431,14 +431,14 @@ public static async Task GetOrCreateContact(this IDbConnection db, Appl ExternalRef = user.Id, CreatedDate = DateTime.UtcNow, }; - sub.Id = (int) await db.InsertAsync(sub, selectIdentity: true); + sub.Id = (int) db.Insert(sub, selectIdentity: true); } return sub; } - public static async Task GetOrCreateContact(this IDbConnection db, CreateEmailBase request) + public static Contact GetOrCreateContact(this IDbConnection db, CreateEmailBase request) { - var sub = await db.SingleAsync(x => x.EmailLower == request.Email.ToLower()); + var sub = db.Single(x => x.EmailLower == request.Email.ToLower()); if (sub == null) { sub = new Contact @@ -452,7 +452,7 @@ public static async Task GetOrCreateContact(this IDbConnection db, Crea ExternalRef = Guid.NewGuid().ToString("N"), CreatedDate = DateTime.UtcNow, }; - sub.Id = (int) await db.InsertAsync(sub, selectIdentity: true); + sub.Id = (int) db.Insert(sub, selectIdentity: true); } return sub; } diff --git a/MyApp.ServiceInterface/CreatorKit/SendMailRunCommand.cs b/MyApp.ServiceInterface/CreatorKit/SendMailRunCommand.cs index 2b23b86..db7c841 100644 --- a/MyApp.ServiceInterface/CreatorKit/SendMailRunCommand.cs +++ b/MyApp.ServiceInterface/CreatorKit/SendMailRunCommand.cs @@ -13,32 +13,31 @@ namespace MyApp.ServiceInterface.CreatorKit; [Tag(Tags.CreatorKit)] [Worker(Databases.CreatorKit)] public class SendMailRunCommand( - ILogger log, + ILogger logger, IBackgroundJobs jobs, IDbConnectionFactory dbFactory, EmailProvider emailProvider) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(SendMailRun request, CancellationToken token) + protected override void Run(SendMailRun request) { + var log = Request.CreateJobLogger(jobs, logger); var job = Request.GetBackgroundJob(); - using var db = await dbFactory.OpenDbConnectionAsync(Databases.CreatorKit, token:token); - var msgIdsToSend = await db.ColumnAsync(db.From() + using var db = dbFactory.Open(Databases.CreatorKit); + var msgIdsToSend = db.Column(db.From() .Where(x => x.MailRunId == request.Id && x.CompletedDate == null && x.StartedDate == null) - .Select(x => x.Id), token: token); + .Select(x => x.Id)); if (msgIdsToSend.Count == 0) { log.LogInformation("No remaining unsent Messages to send for MailRun {Id}", request.Id); - jobs.UpdateJobStatus(new(job, log:$"No remaining unsent Messages to send for MailRun {request.Id}")); return; } - await db.UpdateOnlyAsync(() => new MailRun { SentDate = DateTime.UtcNow }, - where:x => x.Id == request.Id && x.SentDate == null, token: token); + db.UpdateOnly(() => new MailRun { SentDate = DateTime.UtcNow }, + where:x => x.Id == request.Id && x.SentDate == null); log.LogInformation("Sending {Count} Messages for MailRun {Id}", msgIdsToSend.Count, request.Id); - jobs.UpdateJobStatus(new(job, progress:0.05, log:$"Sending {msgIdsToSend.Count} Messages for MailRun {request.Id}")); var i = 0; foreach (var msgId in msgIdsToSend) @@ -48,45 +47,42 @@ protected override async Task RunAsync(SendMailRun request, CancellationToken to var progress = ++i / (double)msgIdsToSend.Count * 0.95 + 0.05; jobs.UpdateJobStatus(new(job, progress:progress, log:$"Sending Message {msgId} for MailRun {request.Id}")); - var msg = await db.SingleByIdAsync(msgId, token: token); + var msg = db.SingleById(msgId); if (msg.CompletedDate != null) { log.LogWarning("MailMessageRun {Id} has already been sent", msg.Id); - jobs.UpdateJobStatus(new(job, log:$"MailMessageRun {msg.Id} has already been sent")); continue; } // ensure message is only sent once - if (await db.UpdateOnlyAsync(() => new MailMessageRun { StartedDate = DateTime.UtcNow }, - where: x => x.Id == request.Id && x.StartedDate == null, token: token) == 1) + if (db.UpdateOnly(() => new MailMessageRun { StartedDate = DateTime.UtcNow }, + where: x => x.Id == request.Id && x.StartedDate == null) == 1) { try { emailProvider.Send(msg.Message); - await db.UpdateOnlyAsync(() => new MailMessageRun { CompletedDate = DateTime.UtcNow }, - where: x => x.Id == request.Id, token: token); + db.UpdateOnly(() => new MailMessageRun { CompletedDate = DateTime.UtcNow }, + where: x => x.Id == request.Id); } catch (Exception e) { var error = e.ToResponseStatus(); - await db.UpdateOnlyAsync(() => new MailMessageRun { Error = error }, - where: x => x.Id == request.Id, token: token); + db.UpdateOnly(() => new MailMessageRun { Error = error }, + where: x => x.Id == request.Id); } } } catch (Exception e) { var error = e.ToResponseStatus(); - await db.UpdateOnlyAsync(() => new MailMessageRun + db.UpdateOnly(() => new MailMessageRun { Error = error - }, where: x => x.Id == msgId, token: token); + }, where: x => x.Id == msgId); log.LogError(e, "Error sending MailMessageRun {Id}: {Message}", msgId, e.Message); - jobs.UpdateJobStatus(new(job, log:$"Error sending MailMessageRun {msgId}: {e.Message}")); } } } - } diff --git a/MyApp.ServiceInterface/CreatorKit/SendMessagesCommand.cs b/MyApp.ServiceInterface/CreatorKit/SendMessagesCommand.cs index 0b0d634..75cbf88 100644 --- a/MyApp.ServiceInterface/CreatorKit/SendMessagesCommand.cs +++ b/MyApp.ServiceInterface/CreatorKit/SendMessagesCommand.cs @@ -18,22 +18,22 @@ public class SendMessages [Tag(Tags.CreatorKit)] [Worker(Databases.CreatorKit)] public class SendMessagesCommand(IDbConnectionFactory dbFactory, EmailProvider emailProvider) - : AsyncCommand + : SyncCommand { - protected override async Task RunAsync(SendMessages request, CancellationToken token) + protected override void Run(SendMessages request) { - using var db = await dbFactory.OpenDbConnectionAsync(Databases.CreatorKit, token: token); + using var db = dbFactory.Open(Databases.CreatorKit); foreach (var msg in request.Messages.Safe()) { if (msg.CompletedDate != null) throw new Exception($"Message {msg.Id} has already been sent"); - msg.Id = (int) await db.InsertAsync(msg, selectIdentity:true, token: token); + msg.Id = (int) db.Insert(msg, selectIdentity:true); // ensure message is only sent once - if (await db.UpdateOnlyAsync(() => new MailMessage { StartedDate = DateTime.UtcNow, Draft = false }, - where: x => x.Id == msg.Id && (x.StartedDate == null), token: token) == 1) + if (db.UpdateOnly(() => new MailMessage { StartedDate = DateTime.UtcNow, Draft = false }, + where: x => x.Id == msg.Id && x.StartedDate == null) == 1) { try { @@ -42,13 +42,13 @@ protected override async Task RunAsync(SendMessages request, CancellationToken t catch (Exception e) { var error = e.ToResponseStatus(); - await db.UpdateOnlyAsync(() => new MailMessage { Error = error }, - where: x => x.Id == msg.Id, token: token); + db.UpdateOnly(() => new MailMessage { Error = error }, + where: x => x.Id == msg.Id); throw; } - await db.UpdateOnlyAsync(() => new MailMessage { CompletedDate = DateTime.UtcNow }, - where: x => x.Id == msg.Id, token: token); + db.UpdateOnly(() => new MailMessage { CompletedDate = DateTime.UtcNow }, + where: x => x.Id == msg.Id); } } } diff --git a/MyApp.ServiceInterface/Data/AppConfig.cs b/MyApp.ServiceInterface/Data/AppConfig.cs index f14c509..99cb67b 100644 --- a/MyApp.ServiceInterface/Data/AppConfig.cs +++ b/MyApp.ServiceInterface/Data/AppConfig.cs @@ -263,10 +263,10 @@ public void ResetUsersUnreadNotifications(IDbConnection db) "SELECT UserName, Count(*) AS Total FROM Notification WHERE Read = false GROUP BY UserName HAVING COUNT(*) > 0")); } - public async Task ResetUnreadNotificationsForAsync(IDbConnection db, string userName) + public void ResetUnreadNotificationsFor(IDbConnection db, string userName) { UsersUnreadNotifications[userName] = - (int)await db.CountAsync(db.From().Where(x => x.UserName == userName && x.Read == false)); + (int)db.Count(db.From().Where(x => x.UserName == userName && x.Read == false)); } public void ResetUsersUnreadAchievements(IDbConnection db) @@ -275,11 +275,11 @@ public void ResetUsersUnreadAchievements(IDbConnection db) "SELECT UserName, Count(*) AS Total FROM Achievement WHERE Read = false GROUP BY UserName HAVING COUNT(*) > 0")); } - public async Task ResetUserQuestionsAsync(IDbConnection db, string userName) + public void ResetUserQuestions(IDbConnection db, string userName) { - var questionsCount = (int)await db.CountAsync(x => x.CreatedBy == userName); + var questionsCount = (int)db.Count(x => x.CreatedBy == userName); UsersQuestions[userName] = questionsCount; - await db.UpdateOnlyAsync(() => + db.UpdateOnly(() => new UserInfo { QuestionsCount = questionsCount }, x => x.UserName == userName); } diff --git a/MyApp.ServiceInterface/Data/CustomUserSession.cs b/MyApp.ServiceInterface/Data/CustomUserSession.cs index 64133ea..913e0e5 100644 --- a/MyApp.ServiceInterface/Data/CustomUserSession.cs +++ b/MyApp.ServiceInterface/Data/CustomUserSession.cs @@ -40,7 +40,7 @@ public override async Task CreateAsync(ApplicationUser user) claims.Add(new Claim(JwtClaimTypes.Picture, user.ProfilePath)); } - var userId = await db.ScalarAsync("SELECT ROWID FROM AspNetUsers WHERE Id = @Id", new { user.Id }); + var userId = db.Scalar("SELECT ROWID FROM AspNetUsers WHERE Id = @Id", new { user.Id }); if (userId > 0) claims.Add(new Claim(JwtClaimTypes.Subject, $"{userId}")); diff --git a/MyApp.ServiceInterface/Data/DbExtensions.cs b/MyApp.ServiceInterface/Data/DbExtensions.cs index 6060176..5e06358 100644 --- a/MyApp.ServiceInterface/Data/DbExtensions.cs +++ b/MyApp.ServiceInterface/Data/DbExtensions.cs @@ -64,13 +64,13 @@ public static SqlExpression OrderByView(this SqlExpression q, LastEditDate = x.ModifiedDate, }; - public static async Task> PopulatePostsAsync(this IDbConnection db, List posts) => - await db.PopulatePostsAsync(posts.Select(ToPost).ToList()); + public static List PopulatePosts(this IDbConnection db, List posts) => + db.PopulatePosts(posts.Select(ToPost).ToList()); - public static async Task> PopulatePostsAsync(this IDbConnection db, List posts) + public static List PopulatePosts(this IDbConnection db, List posts) { var postIds = posts.Select(x => x.Id).ToSet(); - var fullPosts = await db.SelectAsync(db.From().Where(x => postIds.Contains(x.Id))); + var fullPosts = db.Select(db.From().Where(x => postIds.Contains(x.Id))); var fullPostsMap = fullPosts.ToDictionary(x => x.Id); foreach (var post in posts) @@ -92,16 +92,16 @@ public static async Task> PopulatePostsAsync(this IDbConnection db, L return posts; } - public static async Task IsWatchingPostAsync(this IDbConnection db, string userName, int? postId) => - await db.ExistsAsync(db.From().Where(x => x.UserName == userName && x.PostId == postId)); + public static bool IsWatchingPost(this IDbConnection db, string userName, int? postId) => + db.Exists(db.From().Where(x => x.UserName == userName && x.PostId == postId)); - public static async Task IsWatchingTagAsync(this IDbConnection db, string userName, string tag) => - await db.ExistsAsync(db.From().Where(x => x.UserName == userName && x.Tag == tag)); + public static bool IsWatchingTag(this IDbConnection db, string userName, string tag) => + db.Exists(db.From().Where(x => x.UserName == userName && x.Tag == tag)); - public static async Task NotifyQuestionAuthorIfRequiredAsync(this IDbConnection db, IBackgroundJobs jobs, Post answer) + public static void NotifyQuestionAuthorIfRequired(this IDbConnection db, IBackgroundJobs jobs, Post answer) { // Only add notifications for answers older than 1hr - var post = await db.SingleByIdAsync(answer.ParentId); + var post = db.SingleById(answer.ParentId); if (post?.CreatedBy != null && DateTime.UtcNow - post.CreationDate > TimeSpan.FromHours(1)) { if (!string.IsNullOrEmpty(answer.Summary)) @@ -118,5 +118,4 @@ public static async Task NotifyQuestionAuthorIfRequiredAsync(this IDbConnection } } } - } diff --git a/MyApp.ServiceInterface/EmailTemplateServices.cs b/MyApp.ServiceInterface/EmailTemplateServices.cs index b6075ae..ff5ab0f 100644 --- a/MyApp.ServiceInterface/EmailTemplateServices.cs +++ b/MyApp.ServiceInterface/EmailTemplateServices.cs @@ -32,9 +32,9 @@ public async Task Any(SendNewAnswerEmail request) var answer = await questions.GetAnswerAsPostAsync(answerFile); var postId = answer.ParentId; - var post = await Db.SingleByIdAsync(postId); + var post = Db.SingleById(postId); - var user = await Db.SingleAsync(Db.From().Where(x => x.UserName == request.UserName)); + var user = Db.Single(Db.From().Where(x => x.UserName == request.UserName)); var requestArgs = request.ToObjectDictionary(); var contactArgs = user.ToContactArgs(); var args = requestArgs.Merge(contactArgs); diff --git a/MyApp.ServiceInterface/LeaderboardServices.cs b/MyApp.ServiceInterface/LeaderboardServices.cs index 374cf66..c5fd6a5 100644 --- a/MyApp.ServiceInterface/LeaderboardServices.cs +++ b/MyApp.ServiceInterface/LeaderboardServices.cs @@ -22,7 +22,7 @@ public class LeaderboardServices : Service /// public async Task Any(CalculateLeaderBoard request) { - var statTotals = await Db.SelectAsync(); + var statTotals = Db.Select(); var modelsToExclude = request.ModelsToExclude?.Split(",").ToList() ?? []; // filter to answers only var answers = statTotals.Where(x => FilterSpecificModels(x, modelsToExclude)).ToList(); @@ -67,10 +67,10 @@ public async Task Any(CalculateLeaderBoard request) public async Task Any(CalculateTop1KLeaderboard request) { // Do the same for top 1000 questions - var topQuestions = await Db.SelectAsync(Db.From().OrderByDescending(x => x.Score).Limit(1000)); + var topQuestions = Db.Select(Db.From().OrderByDescending(x => x.Score).Limit(1000)); var postIds = topQuestions.Select(x => x.Id).ToList(); - var statTotals = await Db.SelectAsync(Db.From() + var statTotals = Db.Select(Db.From() .Where(x => Sql.In(x.PostId,postIds))); // filter to answers only @@ -219,7 +219,7 @@ double CalculateWinRate(List answers, string name) public async Task Any(GetLeaderboardStatsByTag request) { - var allStatsForTag = await Db.SelectAsync(@"SELECT st.* + var allStatsForTag = Db.Select(@"SELECT st.* FROM main.StatTotals st WHERE st.PostId in (SELECT Id FROM post p diff --git a/MyApp.ServiceInterface/QuestionServices.cs b/MyApp.ServiceInterface/QuestionServices.cs index cfb35e8..511e1fa 100644 --- a/MyApp.ServiceInterface/QuestionServices.cs +++ b/MyApp.ServiceInterface/QuestionServices.cs @@ -63,8 +63,8 @@ public async Task Any(FindSimilarQuestions request) .OrderBy("rank") .Limit(10); - var results = await dbSearch.SelectAsync(q); - var posts = await Db.PopulatePostsAsync(results); + var results = dbSearch.Select(q); + var posts = Db.PopulatePosts(results); return new FindSimilarQuestionsResponse { @@ -83,14 +83,14 @@ public async Task Any(AskQuestion request) var slug = request.Title.GenerateSlug(200); var summary = request.Body.GenerateSummary(); - var existingPost = await Db.SingleAsync(Db.From().Where(x => x.Title == title)); + var existingPost = Db.Single(Db.From().Where(x => x.Title == title)); if (existingPost != null) throw new ArgumentException($"Question with title '{title}' already used in question {existingPost.Id}", nameof(Post.Title)); var refUrn = request.RefUrn; var postId = refUrn != null && refUrn.StartsWith("stackoverflow.com:") && int.TryParse(refUrn.LastRightPart(':'), out var stackoverflowPostId) - && !await Db.ExistsAsync(x => x.Id == stackoverflowPostId) + && !Db.Exists(x => x.Id == stackoverflowPostId) ? stackoverflowPostId : (int)appConfig.GetNextPostId(); @@ -226,7 +226,7 @@ public async Task Any(AnswerQuestion request) */ public async Task Any(UpdateQuestion request) { - var question = await Db.SingleByIdAsync(request.Id); + var question = Db.SingleById(request.Id); if (question == null) throw HttpError.NotFound("Question does not exist"); @@ -234,7 +234,7 @@ public async Task Any(UpdateQuestion request) var isModerator = Request.GetClaimsPrincipal().HasRole(Roles.Moderator); if (!isModerator && question.CreatedBy != userName) { - var userInfo = await Db.SingleAsync(x => x.UserName == userName); + var userInfo = Db.Single(x => x.UserName == userName); if (userInfo.Reputation < 10) throw HttpError.Forbidden("You need at least 10 reputation to Edit other User's Questions."); } @@ -273,7 +273,7 @@ public async Task Any(UpdateAnswer request) var isModerator = Request.GetClaimsPrincipal().HasRole(Roles.Moderator); if (!isModerator && !answerFile.Name.Contains(userName)) { - var userInfo = await Db.SingleAsync(x => x.UserName == userName); + var userInfo = Db.Single(x => x.UserName == userName); if (userInfo.Reputation < 100) throw HttpError.Forbidden("You need at least 100 reputation to Edit other User's Answers."); } @@ -286,7 +286,7 @@ public async Task Any(UpdateAnswer request) { var createdBy = request.Id.RightPart('-'); var answerCreatorId = !string.IsNullOrEmpty(createdBy) - ? await Db.ScalarAsync(Db.From().Where(x => x.UserName == createdBy).Select(x => x.Id)) + ? Db.Scalar(Db.From().Where(x => x.UserName == createdBy).Select(x => x.Id)) : null; if (answerCreatorId != null) @@ -301,9 +301,9 @@ public async Task Any(UpdateAnswer request) return new UpdateAnswerResponse(); } - public async Task Any(GetQuestion request) + public object Any(GetQuestion request) { - var question = await Db.SingleByIdAsync(request.Id); + var question = Db.SingleById(request.Id); if (question == null) throw HttpError.NotFound($"Question {request.Id} not found"); @@ -550,7 +550,7 @@ public async Task Any(GetLastUpdated request) throw new ArgumentNullException(nameof(request.Id)); var lastUpdated = request.PostId != null - ? await Db.ScalarAsync(Db.From().Where(x => x.PostId == request.PostId) + ? Db.Scalar(Db.From().Where(x => x.PostId == request.PostId) .Select(x => Sql.Max(x.LastUpdated))) : null; diff --git a/MyApp.ServiceInterface/Renderers/RegenerateMetaCommand.cs b/MyApp.ServiceInterface/Renderers/RegenerateMetaCommand.cs index 1e874a8..fdb169f 100644 --- a/MyApp.ServiceInterface/Renderers/RegenerateMetaCommand.cs +++ b/MyApp.ServiceInterface/Renderers/RegenerateMetaCommand.cs @@ -33,13 +33,13 @@ public class RegenerateMetaCommand( var log = Request.CreateJobLogger(jobs, logger); // Whether to rerender the Post HTML - using var db = await dbFactory.OpenDbConnectionAsync(token: token); + using var db = dbFactory.Open(); var localFiles = questions.GetLocalQuestionFiles(id); var remoteFiles = await questions.GetRemoteQuestionFilesAsync(id); - var dbStatTotals = await db.SelectAsync(x => x.PostId == id, token:token); + var dbStatTotals = db.Select(x => x.PostId == id); - using var dbAnalytics = await dbFactory.OpenAsync(Databases.Analytics, token: token); - var allPostVotes = await db.SelectAsync(x => x.PostId == id, token:token); + using var dbAnalytics = dbFactory.Open(Databases.Analytics); + var allPostVotes = db.Select(x => x.PostId == id); var regenerateMeta = question.ForPost != null || await ShouldRegenerateMeta(id, localFiles, remoteFiles, dbStatTotals, allPostVotes, token); @@ -160,7 +160,7 @@ public async Task RegenerateMeta(JobLogger log, IDbConnection db, IDbConnection meta.Id = id; meta.ModifiedDate = now; - var dbPost = await db.SingleByIdAsync(id, token: token); + var dbPost = db.SingleById(id); if (dbPost == null) { log.LogWarning("Post {Id} not found", id); @@ -168,8 +168,8 @@ public async Task RegenerateMeta(JobLogger log, IDbConnection db, IDbConnection } if (dbPost.AnswerCount != answerFiles.Count) { - await db.UpdateOnlyAsync(() => new Post { AnswerCount = answerFiles.Count }, - x => x.Id == id, token: token); + db.UpdateOnly(() => new Post { AnswerCount = answerFiles.Count }, + x => x.Id == id); } var totalPostViews = dbAnalytics.Count(x => x.PostId == id); @@ -210,11 +210,11 @@ public async Task RegenerateMeta(JobLogger log, IDbConnection db, IDbConnection var dbStat = dbStatTotals.FirstOrDefault(x => x.Id == liveStat.Id); if (dbStat == null) { - await db.InsertAsync(liveStat, token:token); + db.Insert(liveStat); } else { - await db.UpdateOnlyAsync(() => new StatTotals + db.UpdateOnly(() => new StatTotals { Id = liveStat.Id, PostId = liveStat.PostId, @@ -224,11 +224,11 @@ public async Task RegenerateMeta(JobLogger log, IDbConnection db, IDbConnection DownVotes = liveStat.DownVotes, StartingUpVotes = liveStat.StartingUpVotes, CreatedBy = liveStat.CreatedBy, - }, x => x.Id == liveStat.Id, token:token); + }, x => x.Id == liveStat.Id); } } - meta.StatTotals = await db.SelectAsync(x => x.PostId == id, token:token); + meta.StatTotals = db.Select(x => x.PostId == id); await questions.WriteMetaAsync(meta); } } diff --git a/MyApp.ServiceInterface/SearchTasksCommand.cs b/MyApp.ServiceInterface/SearchTasksCommand.cs index b37febe..a0945b6 100644 --- a/MyApp.ServiceInterface/SearchTasksCommand.cs +++ b/MyApp.ServiceInterface/SearchTasksCommand.cs @@ -21,7 +21,7 @@ public class SearchTasksCommand(ILogger log, IDbConnectionFa { protected override async Task RunAsync(SearchTasks request, CancellationToken token) { - using var db = await dbFactory.OpenDbConnectionAsync(Databases.Search, token: token); + using var db = dbFactory.Open(Databases.Search); string QuotedValue(string? value) => db.GetDialectProvider().GetQuotedValue(value); var minDate = new DateTime(2008,08,1); @@ -39,8 +39,8 @@ protected override async Task RunAsync(SearchTasks request, CancellationToken to log.LogInformation("[SEARCH] Adding Question {PostId} '{Title}' to Search Index...", id, post.Title); var modifiedDate = post.LastEditDate ?? (post.CreationDate > minDate ? post.CreationDate : minDate); - await db.ExecuteNonQueryAsync($"DELETE FROM {nameof(PostFts)} WHERE rowid = {post.Id}", token: token); - await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( + db.ExecuteNonQuery($"DELETE FROM {nameof(PostFts)} WHERE rowid = {post.Id}"); + db.ExecuteNonQuery($@"INSERT INTO {nameof(PostFts)} ( rowid, {nameof(PostFts.RefId)}, {nameof(PostFts.UserName)}, @@ -54,7 +54,7 @@ await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( {QuotedValue(post.Title + "\n\n" + post.Body)}, {QuotedValue(string.Join(',', post.Tags))}, {QuotedValue(modifiedDate.ToString("yyyy-MM-dd HH:mm:ss"))} - )", token: token); + )"); } else if (request.AddAnswerToIndex != null) { @@ -70,11 +70,11 @@ await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( log.LogInformation("[SEARCH] Adding Answer '{RefId}' to Search Index...", answerId); var modifiedDate = post.LastEditDate ?? (post.CreationDate > minDate ? post.CreationDate : minDate); - await db.ExecuteNonQueryAsync($"DELETE FROM {nameof(PostFts)} where {nameof(PostFts.RefId)} = {QuotedValue(refId)}", token: token); + db.ExecuteNonQuery($"DELETE FROM {nameof(PostFts)} where {nameof(PostFts.RefId)} = {QuotedValue(refId)}"); - var nextId = await db.ScalarAsync("SELECT MAX(rowid) FROM PostFts", token: token); + var nextId = db.Scalar("SELECT MAX(rowid) FROM PostFts"); nextId += 1; - await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( + db.ExecuteNonQuery($@"INSERT INTO {nameof(PostFts)} ( rowid, {nameof(PostFts.RefId)}, {nameof(PostFts.UserName)}, @@ -86,7 +86,7 @@ await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( {QuotedValue(post.CreatedBy)}, {QuotedValue(post.Body)}, {QuotedValue(modifiedDate.ToString("yyyy-MM-dd HH:mm:ss"))} - )", token: token); + )"); } if (request.DeletePosts != null) @@ -94,7 +94,7 @@ await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( foreach (var id in request.DeletePosts) { log.LogInformation("[SEARCH] Deleting Post '{PostId}' from Search Index...", id); - await db.ExecuteNonQueryAsync($"DELETE FROM PostFts where RefId = '{id}' or RefId LIKE '{id}-%'", token: token); + db.ExecuteNonQuery($"DELETE FROM PostFts where RefId = '{id}' or RefId LIKE '{id}-%'"); } } @@ -103,7 +103,7 @@ await db.ExecuteNonQueryAsync($@"INSERT INTO {nameof(PostFts)} ( foreach (var refId in request.DeleteAnswers) { log.LogInformation("[SEARCH] Deleting Answer '{PostId}' from Search Index...", refId); - await db.ExecuteNonQueryAsync($"DELETE FROM PostFts where RefId = @refId or RefId = @refId", new { refId }, token: token); + db.ExecuteNonQuery($"DELETE FROM PostFts where RefId = @refId or RefId = @refId", new { refId }); } } } diff --git a/MyApp.ServiceInterface/UserServices.cs b/MyApp.ServiceInterface/UserServices.cs index d5d0fef..6ac51b8 100644 --- a/MyApp.ServiceInterface/UserServices.cs +++ b/MyApp.ServiceInterface/UserServices.cs @@ -36,7 +36,7 @@ public async Task Any(UpdateUserProfile request) await VirtualFiles.WriteFileAsync(AppData.CombineWith(origPath), originalMs); await VirtualFiles.WriteFileAsync(AppData.CombineWith(profilePath), resizedMs); - await Db.UpdateOnlyAsync(() => new ApplicationUser { + Db.UpdateOnly(() => new ApplicationUser { ProfilePath = profilePath, }, x => x.UserName == userName); @@ -104,12 +104,12 @@ public async Task Any(GetUserAvatar request) return new HttpResult(Svg.GetImage(Svg.Icons.Users), MimeTypes.ImageSvg); } - public async Task Any(UserPostData request) + public object Any(UserPostData request) { var userName = Request.GetClaimsPrincipal().Identity!.Name!; - var allUserPostVotes = await Db.SelectAsync(x => x.PostId == request.PostId && x.UserName == userName); + var allUserPostVotes = Db.Select(x => x.PostId == request.PostId && x.UserName == userName); - var watchingPost = await Db.ExistsAsync(Db.From() + var watchingPost = Db.Exists(Db.From() .Where(x => x.PostId == request.PostId && x.UserName == userName && DateTime.UtcNow > x.AfterDate)); var to = new UserPostDataResponse { @@ -137,7 +137,7 @@ public async Task Any(PostVote request) var refUserName = request.RefId.IndexOf('-') >= 0 ? request.RefId.RightPart('-') - : await Db.ScalarAsync(Db.From().Where(x => x.Id == postId) + : Db.Scalar(Db.From().Where(x => x.Id == postId) .Select(x => x.CreatedBy)); if (userName == refUserName) @@ -215,7 +215,7 @@ public async Task Any(GetLatestAchievements request) { var userName = Request.GetClaimsPrincipal().GetUserName(); - var sumAchievements = await Db.SelectAsync( + var sumAchievements = Db.Select( @"SELECT A.PostId, A.RefId, Sum(A.Score) AS Score, Max(A.CreatedDate) AS CreatedDate, P.Title, p.Slug FROM Achievement A LEFT JOIN Post P on (A.PostId = P.Id) WHERE UserName = @userName @@ -291,12 +291,12 @@ public async Task Any(EnsureApplicationUser request) public async Task Any(ShareContent request) { var postId = request.RefId.LeftPart('-').ToInt(); - var post = await Db.SingleByIdAsync(postId); + var post = Db.SingleById(postId); if (post == null) return HttpResult.Redirect("/404"); string? refUserName = request.UserId != null - ? await Db.ScalarAsync("SELECT UserName FROM AspNetUsers WHERE ROWID = @UserId", new { request.UserId }) + ? Db.Scalar("SELECT UserName FROM AspNetUsers WHERE ROWID = @UserId", new { request.UserId }) : null; var userName = Request.GetClaimsPrincipal().GetUserName(); @@ -319,7 +319,7 @@ public async Task Any(ShareContent request) public async Task Any(FlagContent request) { var postId = request.RefId.LeftPart('-').ToInt(); - var post = await Db.SingleByIdAsync(postId); + var post = Db.SingleById(postId); if (post == null) return HttpError.NotFound("Does not exist"); diff --git a/MyApp.ServiceInterface/WatchingServices.cs b/MyApp.ServiceInterface/WatchingServices.cs index 7502a4e..0267c5d 100644 --- a/MyApp.ServiceInterface/WatchingServices.cs +++ b/MyApp.ServiceInterface/WatchingServices.cs @@ -62,8 +62,8 @@ public async Task Any(WatchStatus request) throw new ArgumentException("PostId or Tag is required", nameof(request.PostId)); var watching = request.PostId != null - ? await Db.IsWatchingPostAsync(userName, request.PostId.Value) - : await Db.IsWatchingTagAsync(userName, request.Tag!); + ? Db.IsWatchingPost(userName, request.PostId.Value) + : Db.IsWatchingTag(userName, request.Tag!); return new BoolResponse { Result = watching }; } diff --git a/MyApp/Components/Account/Pages/Login.razor b/MyApp/Components/Account/Pages/Login.razor index d46d0b4..6bd8dd3 100644 --- a/MyApp/Components/Account/Pages/Login.razor +++ b/MyApp/Components/Account/Pages/Login.razor @@ -97,8 +97,8 @@ if (result.Succeeded) { Logger.LogInformation("User logged in."); - using var db = await DbFactory.OpenDbConnectionAsync(); - await db.UpdateOnlyAsync(() => new ApplicationUser + using var db = DbFactory.Open(); + db.UpdateOnly(() => new ApplicationUser { LastLoginIp = HttpContext.GetRemoteIp(), LastLoginDate = DateTime.UtcNow, diff --git a/MyApp/Components/Account/Pages/Register.razor b/MyApp/Components/Account/Pages/Register.razor index 3e36abb..d188238 100644 --- a/MyApp/Components/Account/Pages/Register.razor +++ b/MyApp/Components/Account/Pages/Register.razor @@ -119,8 +119,8 @@ var userId = await UserManager.GetUserIdAsync(user); - using var db = await DbFactory.OpenDbConnectionAsync(); - await db.InsertAsync(new UserInfo + using var db = DbFactory.Open(); + db.Insert(new UserInfo { UserId = userId, UserName = Input.UserName, diff --git a/MyApp/Components/Pages/Home.razor b/MyApp/Components/Pages/Home.razor index e002479..2a61dea 100644 --- a/MyApp/Components/Pages/Home.razor +++ b/MyApp/Components/Pages/Home.razor @@ -54,7 +54,7 @@ using var db = await DbFactory.OpenAsync(); var q = db.From(); q.OrderByView(Tab); - Posts = await db.SelectAsync(q.Take(50)); + Posts = db.Select(q.Take(50)); Jobs.RunCommand(new RenderHome { Tab = Tab, diff --git a/MyApp/Components/Pages/Questions/Index.razor b/MyApp/Components/Pages/Questions/Index.razor index 268620b..a5e229c 100644 --- a/MyApp/Components/Pages/Questions/Index.razor +++ b/MyApp/Components/Pages/Questions/Index.razor @@ -96,7 +96,7 @@ ResponseStatus? error = null; long? total; - async Task Load() + void Load() { try { @@ -116,8 +116,8 @@ if (int.TryParse(Q, out var postId)) { - using var dbApp = await DbFactory.OpenAsync(); - var post = await dbApp.SingleByIdAsync(postId); + using var dbApp = DbFactory.Open(); + var post = dbApp.SingleById(postId); if (post != null) { HttpContext!.Response.Redirect($"/questions/{post.Id}/{post.Slug}", permanent:true); @@ -125,7 +125,7 @@ } } - using var dbSearch = await DbFactory.OpenAsync(Databases.Search); + using var dbSearch = DbFactory.Open(Databases.Search); var q = dbSearch.From(); var search = Q.Trim(); @@ -141,21 +141,21 @@ q.OrderByView(Tab); - List postsFts = await dbSearch.SelectAsync(q + List postsFts = dbSearch.Select(q .Select("RefId, substring(Body,0,400) as Body, ModifiedDate") .Skip(skip) .Take(take)); total = dbSearch.Count(q); - using var db = await DbFactory.OpenAsync(); - posts = await db.PopulatePostsAsync(postsFts); + using var db = DbFactory.Open(); + posts = db.PopulatePosts(postsFts); } else { - using var db = await DbFactory.OpenAsync(); + using var db = DbFactory.Open(); var q = db.From(); - posts = await db.SelectAsync(q + posts = db.Select(q .OrderByView(Tab) .Skip(skip) .Take(take)); @@ -169,5 +169,5 @@ } } - protected override Task OnInitializedAsync() => Load(); + protected override void OnInitialized() => Load(); } \ No newline at end of file diff --git a/MyApp/Components/Pages/Questions/LiveAnswers.razor b/MyApp/Components/Pages/Questions/LiveAnswers.razor index f49b687..086359e 100644 --- a/MyApp/Components/Pages/Questions/LiveAnswers.razor +++ b/MyApp/Components/Pages/Questions/LiveAnswers.razor @@ -191,7 +191,7 @@ using var db = HostContext.AppHost.GetDbConnection(); var userName = HttpContext!.User.GetUserName(); - var actualAnswers = (await db.SelectAsync(x => x.PostId == Id)).Where(x => x.Id.Contains('-')).ToList(); + var actualAnswers = (db.Select(x => x.PostId == Id)).Where(x => x.Id.Contains('-')).ToList(); var expectedAnswers = AppConfig.GetAnswerModelUsersFor(userName); var questionFiles = await QuestionsProvider.GetQuestionAsync(Id); @@ -214,7 +214,7 @@ await AnswerNotifier.ListenForNewAnswersAsync(Id, TimeSpan.FromSeconds(5)); - actualAnswers = (await db.SelectAsync(x => x.PostId == Id)).Where(x => x.Id.Contains('-')).ToList(); + actualAnswers = db.Select(x => x.PostId == Id).Where(x => x.Id.Contains('-')).ToList(); pendingCount = expectedAnswers.Count - actualAnswers.Count; if (pendingCount <= 0) break; diff --git a/MyApp/Components/Pages/Questions/Tagged.razor b/MyApp/Components/Pages/Questions/Tagged.razor index d439b93..682affb 100644 --- a/MyApp/Components/Pages/Questions/Tagged.razor +++ b/MyApp/Components/Pages/Questions/Tagged.razor @@ -79,7 +79,7 @@ ResponseStatus? error; long? total; - async Task Load() + void Load() { try { @@ -92,10 +92,10 @@ if (Use == "db") { - using var db = await DbFactory.OpenAsync(); + using var db = DbFactory.Open(); var q = db.From() .WhereContainsTag(selectedTag); - posts = await db.SelectAsync(q + posts = db.Select(q .OrderByView(Tab) .Skip(Page > 1 ? (Page - 1) * PageSize : 0) .Take(PageSize.ToPageSize())); @@ -103,19 +103,19 @@ } else //search { - using var dbSearch = await DbFactory.OpenAsync(Databases.Search); + using var dbSearch = DbFactory.Open(Databases.Search); var q = dbSearch.From(); q.WhereContainsTag(selectedTag); q.OrderByView(Tab); - List postsFts = await dbSearch.SelectAsync(q + List postsFts = dbSearch.Select(q .Select("RefId, substring(Body,0,400) as Body, ModifiedDate") .Skip(Page > 1 ? (Page - 1) * PageSize : 0) .Take(PageSize.ToPageSize())); total = dbSearch.Count(q); - using var db = await DbFactory.OpenAsync(); - posts = await db.PopulatePostsAsync(postsFts); + using var db = DbFactory.Open(); + posts = db.PopulatePosts(postsFts); } } catch (Exception ex) @@ -124,5 +124,5 @@ } } - protected override Task OnInitializedAsync() => Load(); + protected override void OnInitialized() => Load(); } \ No newline at end of file diff --git a/MyApp/Components/Shared/WatchingContent.razor b/MyApp/Components/Shared/WatchingContent.razor index fe89c3b..ee51505 100644 --- a/MyApp/Components/Shared/WatchingContent.razor +++ b/MyApp/Components/Shared/WatchingContent.razor @@ -1,5 +1,4 @@ -@using MyApp.Data -@using MyApp.ServiceInterface.App +@using MyApp.ServiceInterface.App @using ServiceStack.Jobs @inject IDbConnectionFactory DbFactory @inject IBackgroundJobs Jobs @@ -45,17 +44,17 @@ string Type => PostId != null ? nameof(Post) : nameof(Tag); bool? Watching { get; set; } - protected override async Task OnInitializedAsync() + protected override void OnInitialized() { var userName = HttpContext.GetUserName(); if (userName == null) return; - using var db = await DbFactory.OpenAsync(); + using var db = DbFactory.Open(); Watching = PostId != null - ? await db.IsWatchingPostAsync(userName, PostId) + ? db.IsWatchingPost(userName, PostId) : Tag != null - ? await db.IsWatchingTagAsync(userName, Tag) + ? db.IsWatchingTag(userName, Tag) : null; if (Unsubscribe == true) diff --git a/MyApp/Configure.AppHost.cs b/MyApp/Configure.AppHost.cs index fa8efb7..689df0b 100644 --- a/MyApp/Configure.AppHost.cs +++ b/MyApp/Configure.AppHost.cs @@ -106,13 +106,13 @@ public async Task PrerenderSitemapAsync(ServiceStackHost appHost, string distDir var sw = Stopwatch.StartNew(); using var db = await appHost.Resolve().OpenDbConnectionAsync(); - var feature = await CreateSitemapAsync(log, db, baseUrl); + var feature = CreateSitemap(log, db, baseUrl); await feature.RenderToAsync(distDir); log.LogInformation("Sitemap took {Elapsed} to prerender", sw.Elapsed.Humanize()); } - async Task CreateSitemapAsync(ILogger log, IDbConnection db, string baseUrl) + SitemapFeature CreateSitemap(ILogger log, IDbConnection db, string baseUrl) { var now = DateTime.UtcNow; @@ -122,7 +122,7 @@ DateTime NValidDate(DateTime? date) => date == null DateTime ValidDate(DateTime date) => date.Year < 2000 ? new DateTime(now.Year, date.Month, date.Day) : date; - var posts = await db.SelectAsync(db.From()); + var posts = db.Select(db.From()); var page = 1; var batches = posts.BatchesOf(200); @@ -194,7 +194,6 @@ DateTime ValidDate(DateTime date) => return to; } - } diff --git a/MyApp/Configure.AutoQuery.cs b/MyApp/Configure.AutoQuery.cs index ea0dbbf..73737fb 100644 --- a/MyApp/Configure.AutoQuery.cs +++ b/MyApp/Configure.AutoQuery.cs @@ -19,6 +19,7 @@ public void Configure(IWebHostBuilder builder) => builder services.AddPlugin(new AutoQueryFeature { MaxLimit = 1000, //IncludeTotal = true, + UseDatabaseWriteLocks = true, }); }) .ConfigureAppHost(appHost => { diff --git a/MyApp/Configure.CreatorKit.cs b/MyApp/Configure.CreatorKit.cs index b6ac2ce..c7663d5 100644 --- a/MyApp/Configure.CreatorKit.cs +++ b/MyApp/Configure.CreatorKit.cs @@ -69,7 +69,7 @@ public override async Task ThrowIfNotValidAsync(object dto, IRequest request) // if (checkDb) // { // using var db = HostContext.AppHost.GetDbConnection(request); - // var user = await db.SingleByIdAsync(userId); + // var user = db.SingleById(userId); // if (user == null) // throw new HttpError(ResolveStatusCode(), ResolveErrorCode(), "Your account no longer exists"); //