From 75f4eb11eb1446c4916ee7718a1445ebd4cc0b1f Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 00:59:15 +0700 Subject: [PATCH 1/7] Fix warnings --- .../Domain/ViewModels/MixRoleViewModel.cs | 4 +- .../Controllers/SharedApiController.cs | 4 +- .../Controllers/CommonController.cs | 6 +-- .../Domain/Services/InitCmsService.cs | 5 +- .../Services/MixDbEventService.cs | 2 +- .../ClientsConfiguration.cs | 5 +- .../ExternalLoginViewModel.cs | 6 +-- .../mix.library/Interfaces/IMixCmsService.cs | 2 +- .../mix.library/Interfaces/IMixEdmService.cs | 5 +- .../mix.library/Services/MixCmsService.cs | 12 ++--- .../mix.library/Services/MixEdmService.cs | 6 +-- .../MixBackgroundTaskSubscriber.cs | 2 +- .../ViewModels/MixTemplateViewModel.cs | 2 +- .../Engines/Google/GoogleQueuePublisher.cs | 22 +++++---- .../Engines/Google/GoogleQueueSubscriber.cs | 12 +++-- .../Interfaces/IMixDbDataService.cs | 4 +- .../mix.repodb/Interfaces/IMixDbService.cs | 2 +- .../Repositories/MixRepoDbRepository.cs | 9 +++- .../mix.repodb/Services/MixDbDataService.cs | 48 +++++++++++++++---- .../mix.repodb/Services/MixDbService.cs | 41 +++++++++++++--- .../MixDatabaseRelationshipViewModel.cs | 9 +++- .../Interfaces/IMixMemoryCacheService.cs | 2 +- .../Services/BaseHubClientService.cs | 2 +- .../mix.service/Services/MixLogService.cs | 11 ++--- .../Services/MixMemoryCacheService.cs | 2 +- .../Services/MixPermissionService.cs | 7 +-- src/platform/mix.service/mix.service.csproj | 4 +- .../mix.shared/Dtos/SearchMixDbRequestDto.cs | 4 +- .../Services/AppSettingServiceBase.cs | 2 +- .../mix.shared/Services/HttpService.cs | 7 +-- .../Services/JsonConfigurationServiceBase.cs | 2 +- .../Engines/Mix/MixUploader.cs | 2 +- .../mix.storage.lib/Helpers/ImageHelper.cs | 12 ++--- .../Dtos/FilterOrderDto.cs | 2 +- .../Models/Paypal/PaypalRequest.cs | 2 +- .../Services/EcommerceService.cs | 12 +++-- .../Services/PaypalService.cs | 37 +++++++------- ...ixEcommerceDatabaseAssociationViewModel.cs | 2 +- .../ViewModels/OrderItemViewModel.cs | 2 +- .../ViewModels/WarehouseViewModel.cs | 2 +- .../Controllers/ApiEcommerceController.cs | 13 +++-- .../mix.services.graphql.lib/GraphQLQuery.cs | 17 ++++--- .../Models/DatabaseMetadata.cs | 13 +++-- .../Resolvers/MyFieldResolver.cs | 8 +++- .../Resolvers/NameFieldResolver.cs | 2 +- .../Controllers/GraphqlController.cs | 16 +++---- .../Interfaces/IMixMetadataService.cs | 2 +- .../Interfaces/IMixUserDataService.cs | 2 +- .../Services/MixMetadataService.cs | 43 ++++++++++------- .../Services/MixUserDataService.cs | 10 ++-- .../Controllers/MixUserDataController.cs | 31 ++++++++++-- .../Domain/Base/ViewModelTestBase.cs | 4 +- 52 files changed, 303 insertions(+), 182 deletions(-) diff --git a/src/modules/mix.account/Domain/ViewModels/MixRoleViewModel.cs b/src/modules/mix.account/Domain/ViewModels/MixRoleViewModel.cs index ac35bacc4..ce7232708 100644 --- a/src/modules/mix.account/Domain/ViewModels/MixRoleViewModel.cs +++ b/src/modules/mix.account/Domain/ViewModels/MixRoleViewModel.cs @@ -12,9 +12,7 @@ public MixRoleViewModel() { } - public MixRoleViewModel(MixRole entity, - - UnitOfWorkInfo uowInfo = null) : base(entity, uowInfo) + public MixRoleViewModel(MixRole entity, UnitOfWorkInfo uowInfo = null) : base(entity, uowInfo) { } diff --git a/src/modules/mix.common/Controllers/SharedApiController.cs b/src/modules/mix.common/Controllers/SharedApiController.cs index 8898d2bc7..5564dde5a 100644 --- a/src/modules/mix.common/Controllers/SharedApiController.cs +++ b/src/modules/mix.common/Controllers/SharedApiController.cs @@ -46,7 +46,7 @@ public SharedApiController( IHttpContextAccessor httpContextAccessor, MixQueueMessages mixMemoryMessageQueue, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { _uow = uow; @@ -136,7 +136,7 @@ public async Task ClearCacheAsync(CancellationToken cancellationTo [HttpGet("sitemap")] public async Task Sitemap(CancellationToken cancellationToken = default) { - var file = await _mixCmsService.ParseSitemapAsync(); + var file = await _mixCmsService.ParseSitemapAsync(cancellationToken); return Ok(file); } diff --git a/src/modules/mix.portal/Controllers/CommonController.cs b/src/modules/mix.portal/Controllers/CommonController.cs index 9365bf61b..8d377fa9a 100644 --- a/src/modules/mix.portal/Controllers/CommonController.cs +++ b/src/modules/mix.portal/Controllers/CommonController.cs @@ -43,7 +43,7 @@ public ActionResult Dashboard(string culture) [MixAuthorize] [HttpGet("portal-menus")] - public async Task> PortalMenus() + public async Task> PortalMenus() { var user = await UserManager.GetUserAsync(User); var roles = await UserManager.GetRolesAsync(user); @@ -53,7 +53,7 @@ public ActionResult Dashboard(string culture) - private async Task LoadUserPortalMenus(string[] roles) + private async Task LoadUserPortalMenus(string[] roles) { try { @@ -81,7 +81,7 @@ public ActionResult Dashboard(string culture) } return arrMenus; } - catch (Exception ex) + catch (Exception) { return new(); } diff --git a/src/modules/mix.tenancy/Domain/Services/InitCmsService.cs b/src/modules/mix.tenancy/Domain/Services/InitCmsService.cs index 57c246f29..d518b4ea5 100644 --- a/src/modules/mix.tenancy/Domain/Services/InitCmsService.cs +++ b/src/modules/mix.tenancy/Domain/Services/InitCmsService.cs @@ -42,11 +42,12 @@ public InitCmsService( } - public async Task InitDbContext(InitCmsDto model) + public Task InitDbContext(InitCmsDto model) { _databaseService.InitConnectionStrings(model.ConnectionString, model.DatabaseProvider); - _databaseService.UpdateMixCmsContext(); + + return Task.CompletedTask; } public async Task InitTenantAsync(InitCmsDto model) diff --git a/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs b/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs index ce41ae2b3..49eb0a286 100644 --- a/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs +++ b/src/platform/core/mix.mixdb.event/Services/MixDbEventService.cs @@ -111,7 +111,7 @@ private JObject ParseBody(JObject body, JObject data) { if (strBody.Contains($"[[{prop.Name}]]", StringComparison.OrdinalIgnoreCase)) { - strBody = strBody.Replace($"[[{prop.Name.ToTitleCase()}]]", data.GetValue(prop.Name).ToString()); + strBody = strBody.Replace($"[[{prop.Name.ToTitleCase()}]]", data.GetValue(prop.Name)!.ToString()); } } return JObject.Parse(strBody); diff --git a/src/platform/mix.database/Entities/Account/EntityConfigurations/ClientsConfiguration.cs b/src/platform/mix.database/Entities/Account/EntityConfigurations/ClientsConfiguration.cs index 4f14b1cc2..469b34f77 100644 --- a/src/platform/mix.database/Entities/Account/EntityConfigurations/ClientsConfiguration.cs +++ b/src/platform/mix.database/Entities/Account/EntityConfigurations/ClientsConfiguration.cs @@ -2,14 +2,13 @@ namespace Mix.Database.Entities.Account.EntityConfigurations { - internal class ClientsConfiguration : AccountEntityBaseConfiguration - + public class ClientsConfiguration : AccountEntityBaseConfiguration { public ClientsConfiguration(DatabaseService databaseService) : base(databaseService) { } - public virtual void Configure(EntityTypeBuilder builder) + public override void Configure(EntityTypeBuilder builder) { builder.Property(e => e.Id) .HasCharSet(Config.CharSet) diff --git a/src/platform/mix.identity/Models/AccountViewModels/ExternalLoginViewModel.cs b/src/platform/mix.identity/Models/AccountViewModels/ExternalLoginViewModel.cs index f3e4a6572..a989ac22a 100644 --- a/src/platform/mix.identity/Models/AccountViewModels/ExternalLoginViewModel.cs +++ b/src/platform/mix.identity/Models/AccountViewModels/ExternalLoginViewModel.cs @@ -24,9 +24,9 @@ public class ExternalLoginViewModel public class RegisterExternalBindingModel { - public string? UserName { get; set; } - public string? Email { get; set; } - public string? PhoneNumber { get; set; } + public string UserName { get; set; } + public string Email { get; set; } + public string PhoneNumber { get; set; } public MixExternalLoginProviders Provider { get; set; } public string ExternalAccessToken { get; set; } diff --git a/src/platform/mix.library/Interfaces/IMixCmsService.cs b/src/platform/mix.library/Interfaces/IMixCmsService.cs index 4721e216e..d0c9eae3a 100644 --- a/src/platform/mix.library/Interfaces/IMixCmsService.cs +++ b/src/platform/mix.library/Interfaces/IMixCmsService.cs @@ -4,6 +4,6 @@ public interface IMixCmsService { public string GetAssetFolder(string culture, string domain); public MixTenantSystemModel GetCurrentTenant(); - Task ParseSitemapAsync(); + Task ParseSitemapAsync(CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/src/platform/mix.library/Interfaces/IMixEdmService.cs b/src/platform/mix.library/Interfaces/IMixEdmService.cs index 2407835d1..eb0e1ac05 100644 --- a/src/platform/mix.library/Interfaces/IMixEdmService.cs +++ b/src/platform/mix.library/Interfaces/IMixEdmService.cs @@ -4,8 +4,7 @@ public interface IMixEdmService { public void SetTenantId(int tenantId); public void SetTenant(MixTenantSystemModel tenant); - public Task GetEdmTemplate(string filename); - - public Task SendMailWithEdmTemplate(string subject, string templateName, JObject data, string to, string? cc = null, string? from = null); + public Task GetEdmTemplate(string filename); + public Task SendMailWithEdmTemplate(string subject, string templateName, JObject data, string to, string cc = null, string from = null); } } diff --git a/src/platform/mix.library/Services/MixCmsService.cs b/src/platform/mix.library/Services/MixCmsService.cs index e042741e1..03f3984a2 100644 --- a/src/platform/mix.library/Services/MixCmsService.cs +++ b/src/platform/mix.library/Services/MixCmsService.cs @@ -40,14 +40,14 @@ public MixTenantSystemModel GetCurrentTenant() return CurrentTenant; } - public async Task ParseSitemapAsync() + public async Task ParseSitemapAsync(CancellationToken cancellationToken = default) { try { XNamespace aw = "http://www.sitemaps.org/schemas/sitemap/0.9"; var root = new XElement(aw + "urlset"); - await ParseNavigationsAsync(root); + await ParseNavigationsAsync(root, cancellationToken); await ParsePostsDocAsync(root); string folder = $"wwwroot"; @@ -70,7 +70,7 @@ public async Task ParseSitemapAsync() #region Navigation - protected virtual async Task ParseNavigationsAsync(XElement root) + protected virtual async Task ParseNavigationsAsync(XElement root, CancellationToken cancellation = default) { var navs = await MixNavigationViewModel.GetRepository(_mixdbUow, CacheService).GetListAsync( m => m.MixTenantId == CurrentTenant.Id); @@ -81,11 +81,9 @@ protected virtual async Task ParseNavigationsAsync(XElement root) } } - protected virtual async Task ParsePostsDocAsync(XElement root) + protected virtual async Task ParsePostsDocAsync(XElement root, CancellationToken cancellation = default) { - var posts = await MixPostViewModel.GetRepository(_cmsUow, CacheService).GetListAsync( - m => m.MixTenantId == CurrentTenant.Id); - + var posts = await MixPostViewModel.GetRepository(_cmsUow, CacheService).GetListAsync(m => m.MixTenantId == CurrentTenant.Id, cancellation); foreach (var post in posts) { ParsePostDoc(root, post); diff --git a/src/platform/mix.library/Services/MixEdmService.cs b/src/platform/mix.library/Services/MixEdmService.cs index 1a520e6f7..6a50b93f4 100644 --- a/src/platform/mix.library/Services/MixEdmService.cs +++ b/src/platform/mix.library/Services/MixEdmService.cs @@ -20,7 +20,7 @@ public MixEdmService( _queueService = queueService; } - public async Task GetEdmTemplate(string filename) + public async Task GetEdmTemplate(string filename) { var edmTemplate = await MixTemplateViewModel.GetRepository(_uow, CacheService).GetSingleAsync( m => m.FolderType == MixTemplateFolderType.Edms @@ -31,8 +31,8 @@ public MixEdmService( public virtual async Task SendMailWithEdmTemplate( string subject, string templateName, JObject data, string to, - string? cc = null, - string? from = null) + string cc = null, + string from = null) { var template = await GetEdmTemplate(templateName); if (template == null) diff --git a/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs b/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs index 3190a8167..afe14deec 100644 --- a/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs +++ b/src/platform/mix.library/Subscribers/MixBackgroundTaskSubscriber.cs @@ -98,7 +98,7 @@ private async Task SendMail(MessageQueueModel model) } - private async Task SendMessage(string message, bool result, Exception? ex = null) + private async Task SendMessage(string message, bool result, Exception ex = null) { SignalRMessageModel msg = new() { diff --git a/src/platform/mix.library/ViewModels/MixTemplateViewModel.cs b/src/platform/mix.library/ViewModels/MixTemplateViewModel.cs index e117a9e0f..f60b3f5a5 100644 --- a/src/platform/mix.library/ViewModels/MixTemplateViewModel.cs +++ b/src/platform/mix.library/ViewModels/MixTemplateViewModel.cs @@ -9,7 +9,7 @@ public sealed class MixTemplateViewModel public int MixTenantId { get; set; } public string Content { get; set; } public string Extension { get; set; } - public string? FileFolder { get; set; } + public string FileFolder { get; set; } public string FileName { get; set; } public MixTemplateFolderType FolderType { get; set; } public string Scripts { get; set; } diff --git a/src/platform/mix.queue/Engines/Google/GoogleQueuePublisher.cs b/src/platform/mix.queue/Engines/Google/GoogleQueuePublisher.cs index 8a301d658..001ab6e4a 100644 --- a/src/platform/mix.queue/Engines/Google/GoogleQueuePublisher.cs +++ b/src/platform/mix.queue/Engines/Google/GoogleQueuePublisher.cs @@ -33,10 +33,13 @@ private void InitializeQueue(string topicName) CreateTopic(topicName); var googleCredential = GoogleCredential.FromFile(_queueSetting.CredentialFile); - var createSettings = new PublisherClient.ClientCreationSettings(credentials: googleCredential.ToChannelCredentials()); - var toppicName = new TopicName(_queueSetting.ProjectId, topicName); - var publisher = PublisherClient.CreateAsync(toppicName, createSettings); - _publisher = publisher.Result; + var publisherClientBuilder = new PublisherClientBuilder + { + Credential = googleCredential, + TopicName = new TopicName(_queueSetting.ProjectId, topicName) + }; + + _publisher = publisherClientBuilder.Build(); } } @@ -44,10 +47,13 @@ private Topic CreateTopic(string topicId) { try { - PublisherServiceApiClientBuilder builder = new PublisherServiceApiClientBuilder(); - builder.CredentialsPath = _queueSetting.CredentialFile; - PublisherServiceApiClient publisher = builder.Build(); - TopicName topicName = new TopicName(_queueSetting.ProjectId, topicId); + var builder = new PublisherServiceApiClientBuilder + { + CredentialsPath = _queueSetting.CredentialFile + }; + + var publisher = builder.Build(); + var topicName = new TopicName(_queueSetting.ProjectId, topicId); return publisher.CreateTopic(topicName); } catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists) diff --git a/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs b/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs index 218db033d..f4bbd3e2b 100644 --- a/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs +++ b/src/platform/mix.queue/Engines/Google/GoogleQueueSubscriber.cs @@ -40,10 +40,14 @@ private void InitializeQueue(string topicId, string subscriptionId) CreateSubscription(topicId, subscriptionId); _subscriptionName = new SubscriptionName(_queueSetting.ProjectId, subscriptionId); var googleCredential = GoogleCredential.FromFile(_queueSetting.CredentialFile); - var createSettings = new SubscriberClient.ClientCreationSettings( - credentials: googleCredential.ToChannelCredentials()); - var subscriber = SubscriberClient.CreateAsync(_subscriptionName, createSettings); - _subscriber = subscriber.Result; + + var builder = new SubscriberClientBuilder + { + Credential = googleCredential, + SubscriptionName = _subscriptionName + }; + + _subscriber = builder.Build(); } } diff --git a/src/platform/mix.repodb/Interfaces/IMixDbDataService.cs b/src/platform/mix.repodb/Interfaces/IMixDbDataService.cs index fe6fd0fa7..6ea38f458 100644 --- a/src/platform/mix.repodb/Interfaces/IMixDbDataService.cs +++ b/src/platform/mix.repodb/Interfaces/IMixDbDataService.cs @@ -8,13 +8,13 @@ namespace Mix.RepoDb.Interfaces { - public interface IMixDbDataService: IDisposable + public interface IMixDbDataService : IDisposable { public Task GetSingleByParent(string tableName, MixContentType parentType, object parentId, bool loadNestedData = false); public Task> GetMyData(string tableName, SearchMixDbRequestDto req, string username); - public Task GetMyDataById(string tableName, string username, int id, bool loadNestedData); + public Task GetMyDataById(string tableName, string username, int id, bool loadNestedData); public Task GetById(string tableName, int id, bool loadNestedData); diff --git a/src/platform/mix.repodb/Interfaces/IMixDbService.cs b/src/platform/mix.repodb/Interfaces/IMixDbService.cs index 10dc108f8..e92c11136 100644 --- a/src/platform/mix.repodb/Interfaces/IMixDbService.cs +++ b/src/platform/mix.repodb/Interfaces/IMixDbService.cs @@ -9,7 +9,7 @@ public interface IMixDbService { public Task> GetMyData(string tableName, SearchMixDbRequestDto req, string username); - public Task GetMyDataById(string tableName, string username, int id, bool loadNestedData); + public Task GetMyDataById(string tableName, string username, int id, bool loadNestedData); public Task GetById(string tableName, int id, bool loadNestedData); diff --git a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs index 716cd5efa..b02cb8304 100644 --- a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs +++ b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs @@ -159,10 +159,15 @@ private List ParseSearchQuery(IEnumerable searchQu List queries = new(); foreach (var item in searchQueryFields) { + if (item.Value is null) + { + continue; + } + Operation op = ParseMixOperator(item); - if (op == Operation.In || op == Operation.NotIn && item.Value != null) + if (op == Operation.In || op == Operation.NotIn) { - queries.Add(new QueryField(item.FieldName, op, item.Value.ToString().Split(','))); + queries.Add(new QueryField(item.FieldName, op, item.Value.ToString()!.Split(','))); } else { diff --git a/src/platform/mix.repodb/Services/MixDbDataService.cs b/src/platform/mix.repodb/Services/MixDbDataService.cs index 19286b0c1..180eca38e 100644 --- a/src/platform/mix.repodb/Services/MixDbDataService.cs +++ b/src/platform/mix.repodb/Services/MixDbDataService.cs @@ -70,7 +70,7 @@ public MixDbDataService( #region Methods - public async void SetUOW(UnitOfWorkInfo uow) + public void SetUOW(UnitOfWorkInfo uow) { _repository.SetDbConnection(uow); } @@ -107,7 +107,7 @@ public async Task> GetMyData(string tableName, Sear return await GetResult(tableName, queries, paging, req.LoadNestedData); } - public async Task GetMyDataById(string tableName, string username, int id, bool loadNestedData) + public async Task GetMyDataById(string tableName, string username, int id, bool loadNestedData) { _repository.InitTableName(tableName); var queries = new List() @@ -122,13 +122,23 @@ public async Task GetMyDataById(string tableName, string username, int { var data = ReflectionHelper.ParseObject(obj); var database = await GetMixDatabase(tableName); + + if (database is null) + { + return default; + } + foreach (var item in database.Relationships) { if (loadNestedData) { - List associationQueries = GetAssociationQueries(item.SourceDatabaseName, item.DestinateDatabaseName, id); var associations = await _associationRepository.GetListByAsync(associationQueries); + if (associations is null) + { + continue; + } + if (associations.Count > 0) { var nestedIds = JArray.FromObject(associations).Select(m => m.Value(ChildIdFieldName)).ToList(); @@ -145,8 +155,10 @@ public async Task GetMyDataById(string tableName, string username, int } return data; } + return default; } + public async Task GetById(string tableName, int id, bool loadNestedData) { _repository.InitTableName(tableName); @@ -163,7 +175,6 @@ public async Task GetMyDataById(string tableName, string username, int return default; } - public async Task GetSingleBy(string tableName, List queries) { _repository.InitTableName(tableName); @@ -181,8 +192,6 @@ public async Task CreateData(string tableName, JObject data) var obj = await ParseDto(tableName, data); return await _repository.InsertAsync(obj); } - - #endregion #region Helper @@ -195,6 +204,12 @@ public static string GetCacheFolder(string databaseName) private async Task LoadNestedData(string tableName, JObject data) { var database = await GetMixDatabase(tableName); + + if (database is null) + { + return; + } + foreach (var item in database.Relationships) { List queries = GetAssociationQueries(item.SourceDatabaseName, item.DestinateDatabaseName, data.Value("id")); @@ -217,6 +232,10 @@ private async Task> GetResult(string tableName, IEn var items = new List(); var database = await GetMixDatabase(tableName); + if (database is null) + { + return new PagingResponseModel(); + } foreach (var item in result.Items) { @@ -241,10 +260,11 @@ private async Task> GetResult(string tableName, IEn } items.Add(data); } + return new PagingResponseModel { Items = items, PagingData = result.PagingData }; } - private List GetAssociationQueries(string parentDatabaseName = null, string childDatabaseName = null, int? parentId = null, int? childId = null) + private List GetAssociationQueries(string? parentDatabaseName = null, string? childDatabaseName = null, int? parentId = null, int? childId = null) { var queries = new List(); if (!string.IsNullOrEmpty(parentDatabaseName)) @@ -266,7 +286,7 @@ private List GetAssociationQueries(string parentDatabaseName = null, return queries; } - private async Task GetMixDatabase(string tableName) + private async Task GetMixDatabase(string tableName) { return await _memoryCache.TryGetValueAsync( tableName, @@ -284,6 +304,11 @@ private async Task> BuildSearchQueryAsync(string tableName, Sea if (request.ParentId.HasValue) { var database = await GetMixDatabase(tableName); + if (database is null) + { + return queries; + } + if (database.Type == MixDatabaseType.AdditionalData || database.Type == MixDatabaseType.GuidAdditionalData) { queries.Add(new(ParentIdFieldName, request.ParentId)); @@ -398,6 +423,11 @@ private async Task ParseDto(string tableName, JObject dto) { JObject result = new(); var database = await GetMixDatabase(tableName); + if (database is null) + { + return result; + } + var encryptedColumnNames = database.Columns .Where(m => m.ColumnConfigurations.IsEncrypt) .Select(c => c.SystemName) @@ -433,7 +463,7 @@ private async Task ParseDto(string tableName, JObject dto) if (!result.ContainsKey(IdFieldName)) { - result.Add(new JProperty(IdFieldName, null)); + result.Add(new JProperty(IdFieldName)); if (!result.ContainsKey(CreatedDateFieldName)) { result.Add(new JProperty(CreatedDateFieldName, DateTime.UtcNow)); diff --git a/src/platform/mix.repodb/Services/MixDbService.cs b/src/platform/mix.repodb/Services/MixDbService.cs index e4a4115c2..f895299bf 100644 --- a/src/platform/mix.repodb/Services/MixDbService.cs +++ b/src/platform/mix.repodb/Services/MixDbService.cs @@ -190,6 +190,11 @@ public async Task ParseDataAsync(string tableName, dynamic obj) { var data = ReflectionHelper.ParseObject(obj); var db = await GetMixDatabase(tableName); + if (db is null) + { + return data; + } + var jsonColumns = db.Columns.Where( c => c.DataType == MixDataType.Json || c.DataType == MixDataType.ArrayMedia @@ -257,6 +262,11 @@ public async Task ParseDataAsync(string tableName, dynamic obj) private async Task LoadNestedData(int id, JObject data, string tableName) { var database = await GetMixDatabase(tableName); + if (database is null) + { + return; + } + _repository.InitTableName(tableName); foreach (var item in database.Relationships) { @@ -268,6 +278,11 @@ private async Task LoadNestedData(int id, JObject data, string tableName) _repository.InitTableName(item.DestinateDatabaseName); List query = new() { new(IdFieldName, Operation.In, nestedIds) }; var nestedData = await _repository.GetListByAsync(query); + if (nestedData is null) + { + continue; + } + JArray result = new(); foreach (var nd in nestedData) { @@ -289,6 +304,10 @@ private async Task> GetResult(string tableName, var items = new List(); var database = await GetMixDatabase(tableName); + if (database is null) + { + return new PagingResponseModel(); + } foreach (var item in result.Items) { @@ -338,7 +357,7 @@ private List GetAssociationQueries(string? parentDatabaseName = null return queries; } - private async Task GetMixDatabase(string tableName) + private async Task GetMixDatabase(string tableName) { return await _memoryCache.TryGetValueAsync( tableName, @@ -356,6 +375,11 @@ private async Task> BuildSearchQueryAsync(string tableName, Sea if (request.ParentId.HasValue) { var database = await GetMixDatabase(tableName); + if (database is null) + { + return queries; + } + if (database.Type == MixDatabaseType.AdditionalData || database.Type == MixDatabaseType.GuidAdditionalData) { queries.Add(new(ParentIdFieldName, request.ParentId)); @@ -499,11 +523,16 @@ public async Task MigrateSystemDatabases() currentDb.MixTenantId = CurrentTenant?.Id ?? 1; currentDb.CreatedDateTime = DateTime.UtcNow; currentDb.Columns = new(); - var cols = columns.Where(c => c.MixDatabaseName == database.SystemName).ToList(); - foreach (var col in cols) + + if (columns is not null) { - currentDb.Columns.Add(new(col, _cmsUow)); + var cols = columns.Where(c => c.MixDatabaseName == database.SystemName).ToList(); + foreach (var col in cols) + { + currentDb.Columns.Add(new(col, _cmsUow)); + } } + await currentDb.SaveAsync(); } if (currentDb is { Columns.Count: > 0 }) @@ -607,7 +636,7 @@ private async Task RestoreFromLocal(MixDatabaseViewModel database) private void GetMembers(ExpandoObject obj, List selectMembers) { var result = obj.ToList(); - foreach (KeyValuePair kvp in result) + foreach (KeyValuePair kvp in result) { if (DefaultProperties.All(m => m != kvp.Key) && selectMembers.All(m => m != kvp.Key)) { @@ -726,7 +755,7 @@ private bool IsLongTextColumn(MixDatabaseColumnViewModel col) return col.DataType == MixDataType.Text | col.DataType == MixDataType.Array | col.DataType == MixDataType.ArrayMedia - | col.DataType == MixDataType.ArrayRadio + | col.DataType == MixDataType.ArrayRadio | col.DataType == MixDataType.Html | col.DataType == MixDataType.Json | col.DataType == MixDataType.TuiEditor; diff --git a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs index 246078175..996d85107 100644 --- a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs @@ -31,7 +31,7 @@ public MixDatabaseRelationshipViewModel(UnitOfWorkInfo unitOfWorkInfo) : base(un { } - public MixDatabaseRelationshipViewModel(MixDatabaseRelationship entity, UnitOfWorkInfo uowInfo = null) + public MixDatabaseRelationshipViewModel(MixDatabaseRelationship entity, UnitOfWorkInfo? uowInfo = null) : base(entity, uowInfo) { } @@ -71,8 +71,13 @@ protected override async Task SaveEntityRelationshipAsync(MixDatabaseRelationshi string parentColIdName = $"{SourceDatabaseName.ToTitleCase()}Id"; if (!Context.MixDatabaseColumn.Any(m => m.MixDatabaseName == DestinateDatabaseName && m.SystemName == parentColIdName)) { - var srcDb = Context.MixDatabase.FirstOrDefault(m => m.SystemName == SourceDatabaseName); var destDb = Context.MixDatabase.FirstOrDefault(m => m.SystemName == DestinateDatabaseName); + + if (destDb is null) + { + return; + } + var refCol = new MixDatabaseColumnViewModel(UowInfo) { MixDatabaseName = DestinateDatabaseName, diff --git a/src/platform/mix.service/Interfaces/IMixMemoryCacheService.cs b/src/platform/mix.service/Interfaces/IMixMemoryCacheService.cs index efecfd217..2c5e4a5ed 100644 --- a/src/platform/mix.service/Interfaces/IMixMemoryCacheService.cs +++ b/src/platform/mix.service/Interfaces/IMixMemoryCacheService.cs @@ -8,6 +8,6 @@ public interface IMixMemoryCacheService public void Remove(object key); - public Task TryGetValueAsync(object key, Func> factory); + public Task TryGetValueAsync(object key, Func> factory); } } diff --git a/src/platform/mix.service/Services/BaseHubClientService.cs b/src/platform/mix.service/Services/BaseHubClientService.cs index 2488ed089..2f29568eb 100644 --- a/src/platform/mix.service/Services/BaseHubClientService.cs +++ b/src/platform/mix.service/Services/BaseHubClientService.cs @@ -118,7 +118,7 @@ private void Init() Connection = new HubConnectionBuilder() .WithUrl(endpoint, options => { - options.AccessTokenProvider = () => Task.FromResult(AccessToken); + options.AccessTokenProvider = async () => await Task.FromResult(AccessToken); }) .WithAutomaticReconnect() .Build(); diff --git a/src/platform/mix.service/Services/MixLogService.cs b/src/platform/mix.service/Services/MixLogService.cs index 385a9ca87..fedfd7fd7 100644 --- a/src/platform/mix.service/Services/MixLogService.cs +++ b/src/platform/mix.service/Services/MixLogService.cs @@ -12,12 +12,7 @@ namespace Mix.Service.Services { public class MixLogService { - static MixLogService() - { - MixEndpointService enpointSrv = new(); - } - - public static async Task LogExceptionAsync(Exception? ex = null, MixErrorStatus? status = MixErrorStatus.ServerError, string? message = null) + public static Task LogExceptionAsync(Exception? ex = null, MixErrorStatus? status = MixErrorStatus.ServerError, string? message = null) { Console.Error.WriteLine(ex); @@ -59,7 +54,11 @@ public static async Task LogExceptionAsync(Exception? ex = null, MixErrorStatus? { Console.Write($"Cannot write log file {filePath}"); // File invalid + + return Task.CompletedTask; } + + return Task.CompletedTask; } } diff --git a/src/platform/mix.service/Services/MixMemoryCacheService.cs b/src/platform/mix.service/Services/MixMemoryCacheService.cs index 695522c6d..68680f598 100644 --- a/src/platform/mix.service/Services/MixMemoryCacheService.cs +++ b/src/platform/mix.service/Services/MixMemoryCacheService.cs @@ -27,7 +27,7 @@ public void Remove(object key) Cache.Remove(key); } - public async Task TryGetValueAsync(object key, Func> factory) + public async Task TryGetValueAsync(object key, Func> factory) { return await Cache.GetOrCreateAsync(key, factory); } diff --git a/src/platform/mix.service/Services/MixPermissionService.cs b/src/platform/mix.service/Services/MixPermissionService.cs index 9fd1e4b8e..685ed9c35 100644 --- a/src/platform/mix.service/Services/MixPermissionService.cs +++ b/src/platform/mix.service/Services/MixPermissionService.cs @@ -31,12 +31,11 @@ public async Task Reload() { if (!GlobalConfigService.Instance.IsInit) { - UnitOfWorkInfo uow = null; + UnitOfWorkInfo uow = new(new MixDbDbContext(_databaseService)); ; try { RoleEndpoints = new Dictionary(); accountDbContext = new MixCmsAccountContext(_databaseService); - uow = new(new MixDbDbContext(_databaseService)); var roles = await accountDbContext.MixRoles.ToListAsync(); @@ -74,10 +73,6 @@ public async Task Reload() } } - } - catch (Exception ex) - { - } finally { diff --git a/src/platform/mix.service/mix.service.csproj b/src/platform/mix.service/mix.service.csproj index 502c541ec..5e0f74e0a 100644 --- a/src/platform/mix.service/mix.service.csproj +++ b/src/platform/mix.service/mix.service.csproj @@ -1,10 +1,10 @@ - + net7.0 enable - enable Mix.Service + enable diff --git a/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs b/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs index e7816b3d3..d408255a4 100644 --- a/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs +++ b/src/platform/mix.shared/Dtos/SearchMixDbRequestDto.cs @@ -30,8 +30,8 @@ public SearchMixDbRequestDto(SearchRequestDto req, HttpRequest request) GuidParentId = guidParentId; } } - public bool LoadNestedData { get; set; } - public List? Queries { get; set; } = new(); + + public List Queries { get; set; } = new(); public int? ParentId { get; set; } public Guid? GuidParentId { get; set; } public string ParentName { get; set; } = default; diff --git a/src/platform/mix.shared/Services/AppSettingServiceBase.cs b/src/platform/mix.shared/Services/AppSettingServiceBase.cs index 62705b99e..63a08816e 100644 --- a/src/platform/mix.shared/Services/AppSettingServiceBase.cs +++ b/src/platform/mix.shared/Services/AppSettingServiceBase.cs @@ -27,7 +27,7 @@ public bool SaveSettings() if (settings != null) { settings.Content = new JObject(new JProperty(_sectionName, JObject.FromObject(AppSettings))).ToString(); - return MixFileHelper.SaveFile(settings) != null; + return MixFileHelper.SaveFile(settings); } else { diff --git a/src/platform/mix.shared/Services/HttpService.cs b/src/platform/mix.shared/Services/HttpService.cs index 46972ca30..6762ed1f0 100644 --- a/src/platform/mix.shared/Services/HttpService.cs +++ b/src/platform/mix.shared/Services/HttpService.cs @@ -25,7 +25,8 @@ public HttpService(IHttpClientFactory httpClientFactory) }; } - public async Task SendHttpRequestModel( + + public async Task SendHttpRequestModel( HttpRequestModel request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -143,7 +144,7 @@ public Task PostAsync(string requestUrl, T1 body, return SendRequestAsync( client => client.PostAsync(requestUrl, content), bearerToken, requestHeaders); } - + public Task PutAsync(string requestUrl, T1 body, string bearerToken = null, List> requestHeaders = null, @@ -155,7 +156,7 @@ public Task PutAsync(string requestUrl, T1 body, client => client.PutAsync(requestUrl, content), bearerToken, requestHeaders); } #region Privates - + private HttpContent CreateHttpContent(T content, string contentType) { switch (contentType) diff --git a/src/platform/mix.shared/Services/JsonConfigurationServiceBase.cs b/src/platform/mix.shared/Services/JsonConfigurationServiceBase.cs index c94d594c3..ef1f88982 100644 --- a/src/platform/mix.shared/Services/JsonConfigurationServiceBase.cs +++ b/src/platform/mix.shared/Services/JsonConfigurationServiceBase.cs @@ -56,7 +56,7 @@ public bool SaveSettings() if (settings != null) { settings.Content = AppSettings.ToString(); - return MixFileHelper.SaveFile(settings) != null; + return MixFileHelper.SaveFile(settings); } else { diff --git a/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs b/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs index d4373e26a..1380abd81 100644 --- a/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs +++ b/src/platform/mix.storage.lib/Engines/Mix/MixUploader.cs @@ -28,7 +28,7 @@ public MixUploader( public override Task UploadStream(FileModel file, string? createdBy, CancellationToken cancellationToken = default) { string? result = null; - file = GetFileModel($"{file.Filename}{file.Extension}", null, null, createdBy); + file = GetFileModel($"{file.Filename}{file.Extension}", file.FileStream, null, createdBy); var saveResult = MixFileHelper.SaveFile(file); if (saveResult) { diff --git a/src/platform/mix.storage.lib/Helpers/ImageHelper.cs b/src/platform/mix.storage.lib/Helpers/ImageHelper.cs index a34b7a83d..09d616193 100644 --- a/src/platform/mix.storage.lib/Helpers/ImageHelper.cs +++ b/src/platform/mix.storage.lib/Helpers/ImageHelper.cs @@ -21,7 +21,7 @@ public static bool IsImageResizeable(string extension) #region Async Methods - public static async Task SaveImageAsync(Stream fileStream, FileModel file, ImageSize size = null) + public static async Task SaveImageAsync(Stream fileStream, FileModel file, ImageSize? size = null) { if (!string.IsNullOrEmpty(file.FileBase64)) { @@ -34,7 +34,7 @@ public static async Task SaveImageAsync(Stream fileStream, FileModel file, } } - private static async Task SaveFileStreamAsync(Stream fileStream, FileModel file, ImageSize size) + private static async Task SaveFileStreamAsync(Stream fileStream, FileModel file, ImageSize? size) { using (Image image = await Image.LoadAsync(fileStream)) { @@ -54,7 +54,7 @@ private static async Task SaveFileStreamAsync(Stream fileStream, FileModel } } - private static async Task SaveBase64Async(FileModel file, ImageSize size) + private static async Task SaveBase64Async(FileModel file, ImageSize? size) { string base64 = file.FileBase64.IndexOf(',') >= 0 ? file.FileBase64.Split(',')[1] @@ -83,7 +83,7 @@ private static async Task SaveBase64Async(FileModel file, ImageSize size) #region Sync Methods - public static bool SaveImage(Stream fileStream, FileModel file, ImageSize size = null) + public static bool SaveImage(Stream fileStream, FileModel file, ImageSize? size = null) { if (!string.IsNullOrEmpty(file.FileBase64)) { @@ -96,7 +96,7 @@ public static bool SaveImage(Stream fileStream, FileModel file, ImageSize size = } } - private static bool SaveFileStream(Stream fileStream, FileModel file, ImageSize size) + private static bool SaveFileStream(Stream fileStream, FileModel file, ImageSize? size) { var format = Image.DetectFormat(fileStream); using (Image image = Image.Load(fileStream)) @@ -117,7 +117,7 @@ private static bool SaveFileStream(Stream fileStream, FileModel file, ImageSize } } - private static bool SaveBase64(FileModel file, ImageSize size) + private static bool SaveBase64(FileModel file, ImageSize? size) { string base64 = file.FileBase64.IndexOf(',') >= 0 ? file.FileBase64.Split(',')[1] diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Dtos/FilterOrderDto.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Dtos/FilterOrderDto.cs index 8d40810b2..13c17b059 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Dtos/FilterOrderDto.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Dtos/FilterOrderDto.cs @@ -27,6 +27,6 @@ public FilterOrderDto(SearchRequestDto req) Direction = SortDirection.Desc; } } - public List? Statuses { get; set; } = new(); + public List Statuses { get; set; } = new(); } } diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs index e5cc3071c..de29732ac 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Models/Paypal/PaypalRequest.cs @@ -186,7 +186,7 @@ public UnitAmount() { } - public UnitAmount(string? currency, double? total) + public UnitAmount(string currency, double? total) { currency_code = currency; value = $"{total}"; diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs index 0d2c480e8..2e2fcfbec 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Services/EcommerceService.cs @@ -299,7 +299,7 @@ public virtual async Task RemoveFromCart( } // Get Payment URL - + var request = await paymentService.GetPaymentRequestAsync(checkoutCart, _paymentConfiguration.Urls.PaymentCartUrl, _paymentConfiguration.Urls.PaymentResponseUrl, cancellationToken); checkoutCart.PaymentRequest = request; await checkoutCart.SaveAsync(cancellationToken); @@ -380,22 +380,24 @@ protected virtual async Task SendPaymentSuccessEdm(OrderViewModel order) } - protected virtual async Task FilterGuestCheckoutCartAsync(OrderViewModel checkoutCart) + protected virtual Task FilterGuestCheckoutCartAsync(OrderViewModel checkoutCart) { checkoutCart.SetUowInfo(EcommerceUow, CacheService); checkoutCart.LastModified = DateTime.UtcNow; checkoutCart.OrderStatus = OrderStatus.WAITING_FOR_PAYMENT; checkoutCart.CreatedDateTime = DateTime.UtcNow; + + return Task.CompletedTask; } - protected virtual async Task FilterCheckoutCartAsync(OrderViewModel checkoutCart, OrderViewModel myCart) + protected virtual Task FilterCheckoutCartAsync(OrderViewModel checkoutCart, OrderViewModel myCart) { myCart.SetUowInfo(EcommerceUow, CacheService); checkoutCart.LastModified = DateTime.UtcNow; checkoutCart.OrderStatus = OrderStatus.WAITING_FOR_PAYMENT; checkoutCart.CreatedDateTime = DateTime.UtcNow; - } - + return Task.CompletedTask; + } } } diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs index ef66bcbc3..4965d888c 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs @@ -32,7 +32,6 @@ public sealed class PaypalService : TenantServiceBase, IPaymentService private readonly UnitOfWorkInfo _cmsUow; private readonly HttpClient _httpClient; private PaypalConfigurations _settings { get; set; } = new PaypalConfigurations(); - protected PayPalAccessToken _token { get; set; } public PayPalAccessToken? Token { get => GetPayPalAccessTokenAsync(); } public PaypalService( IHttpContextAccessor httpContextAccessor, @@ -63,8 +62,8 @@ public async Task GetPaymentRequestAsync( { try { - var createdPayment = await CreatePaypalOrderAsync(order, $"{againUrl.TrimEnd('/')}?orderId={order.Id}", $"{returnUrl.TrimEnd('/')}?orderId={order.Id}"); - var approval_url = createdPayment.links.First(x => x.rel == "approve").href; + var createdPayment = await CreatePaypalOrderAsync(order, $"{againUrl.TrimEnd('/')}?orderId={order.Id}", $"{returnUrl.TrimEnd('/')}?orderId={order.Id}", cancellationToken); + var approval_url = createdPayment!.links.First(x => x.rel == "approve").href; return approval_url; } catch (Exception ex) @@ -85,11 +84,16 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta string? token = response.Value("token"); string? payerId = response.Value("PayerID"); var result = await CaptureOrderResult(token); - if (string.IsNullOrEmpty(result.id) && orderDetail.PaymentStatus == PaymentStatus.SENT) + if (string.IsNullOrEmpty(result?.id) && orderDetail.PaymentStatus == PaymentStatus.SENT) { result = await GetOrderResult(token); } + if (result is null) + { + throw new MixException(MixErrorStatus.Badrequest, "Cannot get order result."); + } + var reference = result.purchase_units[0].reference_id; var status = !string.IsNullOrEmpty(reference) ? PaymentStatus.SUCCESS : PaymentStatus.FAILED; await SaveResponse(result, status, cancellationToken); @@ -105,9 +109,9 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta #region Private - private async Task SaveResponse(PaypalOrderCapturedResponse response, PaymentStatus paymentStatus, CancellationToken cancellationToken) + private async Task SaveResponse(PaypalOrderCapturedResponse? response, PaymentStatus paymentStatus, CancellationToken cancellationToken) { - var resp = new PaypalTransactionResponse(response); + var resp = new PaypalTransactionResponse(response!); var vm = new PaypalTransactionResponseViewModel(resp, _cmsUow); vm.PaymentStatus = paymentStatus; await vm.SaveAsync(cancellationToken); @@ -120,7 +124,6 @@ private async Task SaveOrderRequest(PaypalOrderRequest request, OrderStatus paym await vm.SaveAsync(cancellationToken); } - private HttpClient GetPaypalHttpClient() { var http = new HttpClient @@ -132,13 +135,8 @@ private HttpClient GetPaypalHttpClient() return http; } - private PayPalAccessToken GetPayPalAccessTokenAsync() + private PayPalAccessToken? GetPayPalAccessTokenAsync() { - if (_token != null && _token.expires_at > DateTime.Now) - { - return _token; - } - var clientId = _settings.ClientId; var secret = _settings.SecretKey; @@ -156,13 +154,11 @@ private PayPalAccessToken GetPayPalAccessTokenAsync() HttpResponseMessage response = SendPaypalRequest(request).GetAwaiter().GetResult(); string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - PayPalAccessToken accessToken = JsonConvert.DeserializeObject(content); + PayPalAccessToken? accessToken = JsonConvert.DeserializeObject(content); return accessToken; } - - - private async Task CreatePaypalOrderAsync( + private async Task CreatePaypalOrderAsync( OrderViewModel order, string againUrl, string returnUrl, CancellationToken cancellationToken = default) { @@ -177,13 +173,14 @@ private async Task CreatePaypalOrderAsync( string content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { - PaypalOrderCreatedResponse paypalPaymentCreated = JsonConvert.DeserializeObject(content); + PaypalOrderCreatedResponse? paypalPaymentCreated = JsonConvert.DeserializeObject(content); return paypalPaymentCreated; } + throw new MixException(MixErrorStatus.Badrequest, content); } - private async Task CaptureOrderResult(string orderId) + private async Task CaptureOrderResult(string? orderId) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"v2/checkout/orders/{orderId}/capture"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token); @@ -195,7 +192,7 @@ private async Task CaptureOrderResult(string orderI return result; } - private async Task GetOrderResult(string orderId) + private async Task GetOrderResult(string? orderId) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"v2/checkout/orders/{orderId}"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token); diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/MixEcommerceDatabaseAssociationViewModel.cs b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/MixEcommerceDatabaseAssociationViewModel.cs index 44f07a827..da5e4cee4 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/MixEcommerceDatabaseAssociationViewModel.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/MixEcommerceDatabaseAssociationViewModel.cs @@ -53,7 +53,7 @@ public override async Task Validate(CancellationToken cancellationToken) Errors.Add(new("This association is existed")); } } - public override void InitDefaultValues(string language = null, int? cultureId = null) + public override void InitDefaultValues(string? language = null, int? cultureId = null) { base.InitDefaultValues(language, cultureId); if (Id == default) diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs index e8d85ffef..8dc3fbba0 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/OrderItemViewModel.cs @@ -49,7 +49,7 @@ public OrderItemViewModel(UnitOfWorkInfo unitOfWorkInfo) : base(unitOfWorkInfo) IsCache = false; } - public OrderItemViewModel(OrderItem entity, UnitOfWorkInfo uowInfo = null) : base(entity, uowInfo) + public OrderItemViewModel(OrderItem entity, UnitOfWorkInfo? uowInfo = null) : base(entity, uowInfo) { IsCache = false; } diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs index 380cbe029..a3f5cb77c 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/ViewModels/WarehouseViewModel.cs @@ -34,7 +34,7 @@ public WarehouseViewModel(UnitOfWorkInfo unitOfWorkInfo) : base(unitOfWorkInfo) { } - public WarehouseViewModel(Warehouse entity, UnitOfWorkInfo uowInfo = null) : base(entity, uowInfo) + public WarehouseViewModel(Warehouse entity, UnitOfWorkInfo? uowInfo = null) : base(entity, uowInfo) { } diff --git a/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs b/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs index 6230b38c4..41d2f49b3 100644 --- a/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs +++ b/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs @@ -45,7 +45,7 @@ public ApiEcommerceController( IOrderService orderService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { _ecommerceService = ecommerceService; @@ -84,7 +84,7 @@ public async Task> GetMyOrders(int id, Cancellation var order = await _orderService.GetUserOrder(User, id, cancellationToken); return Ok(order); } - + [MixAuthorize] [HttpGet] [Route("guest-order/{id}")] @@ -142,7 +142,7 @@ public async Task> Checkout(PaymentGateway? gateway, [From var url = await _ecommerceService.Checkout(User, gateway.Value, cart, cancellationToken); return !string.IsNullOrEmpty(url) ? Ok(new JObject(new JProperty("url", url))) : BadRequest(); } - + [HttpPost] [Route("checkout-guest/{gateway}")] public async Task> CheckoutGuest(PaymentGateway? gateway, [FromBody] OrderViewModel cart, CancellationToken cancellationToken = default) @@ -166,7 +166,12 @@ public async Task PaymentResponse([FromQuery] int? orderId, Cancel } var query = HttpUtility.ParseQueryString(Request.QueryString.Value); - var paymentResponse = JObject.FromObject(query!.AllKeys.ToDictionary(k => k, k => query[k])); + if (query is null || query.AllKeys is null) + { + return BadRequest(); + } + + var paymentResponse = JObject.FromObject(query.AllKeys.ToDictionary(k => k, k => query[k])); orderId ??= paymentResponse.Value("vpc_OrderInfo"); if (!orderId.HasValue) { diff --git a/src/services/graphql/mix.services.graphql.lib/GraphQLQuery.cs b/src/services/graphql/mix.services.graphql.lib/GraphQLQuery.cs index 5aa468165..6fd6419cc 100644 --- a/src/services/graphql/mix.services.graphql.lib/GraphQLQuery.cs +++ b/src/services/graphql/mix.services.graphql.lib/GraphQLQuery.cs @@ -8,13 +8,13 @@ namespace Mix.Services.Graphql.Lib { public class GraphQLQuery : ObjectGraphType { - private IDatabaseMetadata _dbMetadata; - private ITableNameLookup _tableNameLookup; - private DbContext _dbContext; + private readonly IDatabaseMetadata _dbMetadata; + private readonly ITableNameLookup _tableNameLookup; + private readonly DbContext _dbContext; public GraphQLQuery( - DbContext dbContext, - IDatabaseMetadata dbMetadata, - ITableNameLookup tableNameLookup) + DbContext dbContext, + IDatabaseMetadata dbMetadata, + ITableNameLookup tableNameLookup) { _dbMetadata = dbMetadata; _tableNameLookup = tableNameLookup; @@ -25,6 +25,11 @@ public GraphQLQuery( foreach (var metaTable in _dbMetadata.GetTableMetadatas()) { var type = assem.GetType(metaTable.AssemblyFullName); + if (type is null) + { + continue; + } + var tableType = new TableType(metaTable, type); var friendlyTableName = metaTable.TableName; _tableNameLookup.GetFriendlyName(metaTable.TableName); diff --git a/src/services/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs b/src/services/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs index cbf66d1d8..6baa9e26e 100644 --- a/src/services/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs +++ b/src/services/graphql/mix.services.graphql.lib/Models/DatabaseMetadata.cs @@ -10,15 +10,15 @@ public sealed class DatabaseMetadata : IDatabaseMetadata { private readonly DbContext _dbContext; private readonly ITableNameLookup _tableNameLookup; - private string _databaseName; private IEnumerable _tables; public DatabaseMetadata(DbContext dbContext, ITableNameLookup tableNameLookup) { _dbContext = dbContext; _tableNameLookup = tableNameLookup; - _databaseName = _dbContext.Database.GetDbConnection().Database; if (_tables == null) + { ReloadMetadata(); + } } public IEnumerable GetTableMetadatas() { @@ -35,10 +35,15 @@ private IReadOnlyList FetchTableMetaData() foreach (var entityType in _dbContext.Model.GetEntityTypes()) { var tableName = entityType.GetTableName(); + if (tableName is null) + { + continue; + } + metaTables.Add(new TableMetadata { TableName = tableName, - AssemblyFullName = entityType.ClrType.FullName, + AssemblyFullName = entityType.ClrType.FullName!, Columns = GetColumnsMetadata(entityType) }); _tableNameLookup.InsertKeyName(tableName); @@ -48,7 +53,7 @@ private IReadOnlyList FetchTableMetaData() } private IReadOnlyList GetColumnsMetadata(IEntityType entityType) { - var tableColumns = new List(); + var tableColumns = new List(); foreach (var propertyType in entityType.GetProperties()) { tableColumns.Add(new ColumnMetadata diff --git a/src/services/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs b/src/services/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs index 16fcc0d8a..f25916f1e 100644 --- a/src/services/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs +++ b/src/services/graphql/mix.services.graphql.lib/Resolvers/MyFieldResolver.cs @@ -23,6 +23,11 @@ public MyFieldResolver(TableMetadata tableMetadata, DbContext dbContext) { var queryable = _dbContext.Query(_tableMetadata.AssemblyFullName); + if (queryable is null) + { + return default; + } + // Get filters var filters = context.Arguments!.Where(c => c.Key != "first" && c.Key != "offset"); string predicates = string.Empty; @@ -36,7 +41,8 @@ public MyFieldResolver(TableMetadata tableMetadata, DbContext dbContext) { predicates += " and "; } - args[paramsCount] = item.Value!.Value; + + args[paramsCount] = item.Value!.Value!; // Note: check for like function https://github.com/StefH/System.Linq.Dynamic.Core/issues/105 predicates += $"{item.Key.ToTitleCase()} == @{paramsCount}"; } diff --git a/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs b/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs index ae1143fae..d4fb483c4 100644 --- a/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs +++ b/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs @@ -30,7 +30,7 @@ private static object GetPropValue(object src, string propName) //{ // throw new InvalidOperationException($"Expected to find property {context.FieldAst.Name} on {context.Source.GetType().Name} but it does not exist."); //} - return value; + return await Task.FromResult(value); } } } diff --git a/src/services/graphql/mix.services.graphql/Controllers/GraphqlController.cs b/src/services/graphql/mix.services.graphql/Controllers/GraphqlController.cs index 5e28fb73d..094a55ac6 100644 --- a/src/services/graphql/mix.services.graphql/Controllers/GraphqlController.cs +++ b/src/services/graphql/mix.services.graphql/Controllers/GraphqlController.cs @@ -56,14 +56,14 @@ public async Task GraphQLPostAsync() return BadRequest(); } - private GraphQLRequest BuildRequest(string query, string? operationName, string? variables = null, string? extensions = null) - => new GraphQLRequest - { - Query = query == "" ? null : query, - OperationName = operationName == "" ? null : operationName, - Variables = _serializer.Deserialize(variables == "" ? null : variables), - Extensions = _serializer.Deserialize(extensions == "" ? null : extensions), - }; + private GraphQLRequest BuildRequest(string? query, string? operationName, string? variables = null, string? extensions = null) + => new GraphQLRequest + { + Query = string.IsNullOrEmpty(query) ? null : query, + OperationName = operationName == "" ? null : operationName, + Variables = _serializer.Deserialize(variables == "" ? null : variables), + Extensions = _serializer.Deserialize(extensions == "" ? null : extensions), + }; private async Task ExecuteGraphQLRequestAsync(GraphQLRequest? request) diff --git a/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixMetadataService.cs b/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixMetadataService.cs index 95d0bd21f..f75d67770 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixMetadataService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixMetadataService.cs @@ -22,7 +22,7 @@ public interface IMixMetadataService public Task DeleteMetadataContentAssociation(int id, CancellationToken cancellationToken = default); - public IQueryable GetQueryableContentIdByMetadataSeoContent(List metadataSeoContents, MixContentType contentType); + public IQueryable? GetQueryableContentIdByMetadataSeoContent(List metadataSeoContents, MixContentType contentType); public IQueryable? GetQueryableMetadataByContentId(int contentId, MixContentType? contentType, string metadataType); } diff --git a/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixUserDataService.cs b/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixUserDataService.cs index 2083cd156..8041f1685 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixUserDataService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Interfaces/IMixUserDataService.cs @@ -14,7 +14,7 @@ public interface IMixUserDataService public Task CreateUserAddress(CreateUserAddressDto dto, MixUser user, CancellationToken cancellationToken = default); - public Task UpdateUserAddress(MixContactAddressViewModel address, MixUser? user, CancellationToken cancellationToken); + public Task UpdateUserAddress(MixContactAddressViewModel address, MixUser user, CancellationToken cancellationToken); public Task UpdateProfile(MixUserDataViewModel profile, CancellationToken cancellationToken = default); } diff --git a/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs b/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs index 2b785f156..c44beb28b 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs @@ -150,13 +150,16 @@ public async Task DeleteMetadataContentAssociation(int id, CancellationToken can return default; } - IQueryable andQueryIds = null; - IQueryable orQueryIds = null; - var andQueries = metadataSeoContents.Where(m => m.IsRequired).ToList(); - var orQueries = metadataSeoContents.Where(m => !m.IsRequired).ToList(); + IQueryable? andQueryIds = null; + IQueryable? orQueryIds = null; + List andQueries = metadataSeoContents.Where(m => m.IsRequired).ToList(); + List orQueries = metadataSeoContents.Where(m => !m.IsRequired).ToList(); foreach (var item in andQueries) { - if (item.Value == null) continue; + if (item.Value is null) + { + continue; + } Expression> predicate = m => m.Type == item.FieldName; @@ -164,25 +167,26 @@ public async Task DeleteMetadataContentAssociation(int id, CancellationToken can if (item.CompareOperator == MixCompareOperator.InRange || item.CompareOperator == MixCompareOperator.NotInRange) { - var array = item.Value.ToString().Split(','); - predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.InRange, - m => array.Contains(m.SeoContent)); - predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.NotInRange, - m => !array.Contains(m.SeoContent)); + var array = item.Value.ToString()!.Split(','); + predicate = predicate + .AndAlsoIf(item.CompareOperator == MixCompareOperator.InRange, m => array.Contains(m.SeoContent)); + + predicate = predicate + .AndAlsoIf(item.CompareOperator == MixCompareOperator.NotInRange, m => !array.Contains(m.SeoContent)); } else { - predicate = predicate.AndAlso(ReflectionHelper.GetExpression( - "SeoContent", item.Value.ToString(), MixCmsHelper.ParseExpressionMethod(item.CompareOperator))); + predicate = predicate + .AndAlso(ReflectionHelper.GetExpression("SeoContent", item.Value.ToString(), MixCmsHelper.ParseExpressionMethod(item.CompareOperator))); } var allowMetadata = _uow.DbContext.MixMetadata.Where(predicate); - var allowedContentIds = from metadata in allowMetadata join association in _uow.DbContext.MixMetadataContentAssociation on metadata.Id equals association.MetadataId where association.MixTenantId == CurrentTenant.Id && association.ContentType == contentType select association.ContentId; + if (andQueryIds == null) { andQueryIds = allowedContentIds.Distinct(); @@ -192,19 +196,23 @@ on metadata.Id equals association.MetadataId andQueryIds = andQueryIds.Where(m => allowedContentIds.Contains(m)); } } + foreach (var item in orQueries) { - if (item.Value == null) continue; + if (item.Value == null) + { + continue; + } Expression> predicate = m => m.Type == item.FieldName; if (item.CompareOperator == MixCompareOperator.InRange || item.CompareOperator == MixCompareOperator.NotInRange) { - var array = item.Value.ToString().Split(','); - predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.InRange, + var array = item.Value.ToString()!.Split(','); + predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.InRange, m => array.Contains(m.SeoContent)); - predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.NotInRange, + predicate = predicate.AndAlsoIf(item.CompareOperator == MixCompareOperator.NotInRange, m => !array.Contains(m.SeoContent)); } else @@ -228,6 +236,7 @@ on metadata.Id equals association.MetadataId orQueryIds = orQueryIds.Concat(allowedContentIds); } } + return andQueries.Count == 0 ? orQueryIds.Distinct() : orQueries.Count == 0 ? andQueryIds.Distinct() : andQueryIds.Where(m => orQueryIds.Contains(m)).Distinct(); diff --git a/src/services/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs b/src/services/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs index 07c0fdfbf..f8321388c 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Services/MixUserDataService.cs @@ -64,15 +64,17 @@ public async Task DeleteUserAddress(int addressId, MixUser user, CancellationTok cancellationToken.ThrowIfCancellationRequested(); var userData = await GetUserDataAsync(user.Id, cancellationToken); - if (userData == null) + if (userData is null || userData.Addresses is null) { throw new MixException(MixErrorStatus.Badrequest, "User Data not existed"); } + var address = userData.Addresses.SingleOrDefault(a => a.Id == addressId); - if (address == null) + if (address is null) { throw new MixException(MixErrorStatus.Badrequest, "Address not existed"); } + await address.DeleteAsync(cancellationToken); } @@ -82,7 +84,7 @@ public async Task CreateUserAddress(CreateUserAddressDto d cancellationToken.ThrowIfCancellationRequested(); var userData = await GetUserDataAsync(user.Id, cancellationToken); - if (userData == null) + if (userData is null) { throw new MixException(MixErrorStatus.Badrequest, "User Data not existed"); } @@ -98,7 +100,7 @@ public async Task CreateUserAddress(CreateUserAddressDto d return userData; } - public async Task UpdateUserAddress(MixContactAddressViewModel address, MixUser? user, CancellationToken cancellationToken) + public async Task UpdateUserAddress(MixContactAddressViewModel address, MixUser user, CancellationToken cancellationToken) { var userData = await GetUserDataAsync(user.Id, cancellationToken); if (address.SysUserDataId != userData.Id) diff --git a/src/services/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs b/src/services/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs index b92a34328..d6eaa4811 100644 --- a/src/services/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs +++ b/src/services/mix-databases/mix.servives.databases/Controllers/MixUserDataController.cs @@ -14,6 +14,7 @@ using Mix.Database.Entities.MixDb; using Mix.SignalR.Interfaces; using Mix.Lib.Interfaces; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace Mix.Services.Databases.Controllers { @@ -24,8 +25,8 @@ public sealed class MixUserDataController : private readonly TenantUserManager _userManager; private readonly IMixUserDataService _userDataService; public MixUserDataController( - IMixUserDataService metadataService, - TenantUserManager userManager, + IMixUserDataService metadataService, + TenantUserManager userManager, IHttpContextAccessor httpContextAccessor, IConfiguration configuration, MixCacheService cacheService, @@ -35,7 +36,7 @@ public MixUserDataController( IQueueService queueService, IPortalHubClientService portalHub, IMixTenantService mixTenantService) - : base(httpContextAccessor, configuration, + : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, uow, queueService, portalHub, mixTenantService) { _userDataService = metadataService; @@ -50,16 +51,21 @@ public MixUserDataController( public async Task> GetUserData(CancellationToken cancellationToken = default) { var user = await _userManager.GetUserAsync(User); + if (user == null) + { + return BadRequest(); + } + var result = await _userDataService.GetUserDataAsync(user.Id, cancellationToken); return Ok(result); } - + [MixAuthorize] [HttpPut("update-profile")] public async Task> UpdateProfile([FromBody] MixUserDataViewModel profile, CancellationToken cancellationToken = default) { var user = await _userManager.GetUserAsync(User); - if (user.Id != profile.ParentId) + if (user?.Id != profile.ParentId) { return BadRequest(); } @@ -77,6 +83,11 @@ public async Task> UpdateProfile([FromBody] M public async Task> AddUserAddress([FromBody] CreateUserAddressDto dto, CancellationToken cancellationToken = default) { var user = await _userManager.GetUserAsync(User); + if (user is null) + { + return BadRequest(); + } + var result = await _userDataService.CreateUserAddress(dto, user, cancellationToken); return Ok(result); } @@ -86,6 +97,11 @@ public async Task> AddUserAddress([FromBody] public async Task> UpdateUserAddress([FromBody] MixContactAddressViewModel address, CancellationToken cancellationToken = default) { var user = await _userManager.GetUserAsync(User); + if (user is null) + { + return BadRequest(); + } + await _userDataService.UpdateUserAddress(address, user, cancellationToken); return Ok(); } @@ -95,6 +111,11 @@ public async Task> UpdateUserAddress([FromBod public async Task DeleteUserAddress(int addressId, CancellationToken cancellationToken = default) { var user = await _userManager.GetUserAsync(User); + if (user is null) + { + return BadRequest(); + } + await _userDataService.DeleteUserAddress(addressId, user, cancellationToken); return Ok(); } diff --git a/src/test/mix.xunittest/Domain/Base/ViewModelTestBase.cs b/src/test/mix.xunittest/Domain/Base/ViewModelTestBase.cs index 41c09e4eb..3850ed40d 100644 --- a/src/test/mix.xunittest/Domain/Base/ViewModelTestBase.cs +++ b/src/test/mix.xunittest/Domain/Base/ViewModelTestBase.cs @@ -56,11 +56,11 @@ public async Task Step_3_Delete() } catch (MixException mex) { - Assert.True(false, mex.Message); + Assert.Fail(mex.Message); } catch (Exception ex) { - Assert.True(false, ex.Message); + Assert.Fail(ex.Message); } } } From 4342b203c9d2bc01cd37c380cd2fb1cc24d759a5 Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 01:02:17 +0700 Subject: [PATCH 2/7] Update mix-heart --- src/platform/core/mix-heart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/core/mix-heart b/src/platform/core/mix-heart index a69718492..54ce82d2d 160000 --- a/src/platform/core/mix-heart +++ b/src/platform/core/mix-heart @@ -1 +1 @@ -Subproject commit a697184921b53d920d7111f098130903672cf7c6 +Subproject commit 54ce82d2d0625e803c4a51e22393a4fd16b848ad From 02ce1cf86a4a99ded6af423e2cc59e723d27ad2e Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 08:48:06 +0700 Subject: [PATCH 3/7] Fix warnings --- .../Controllers/SharedApiController.cs | 4 +- .../Services/RuntimeDbContextService.cs | 16 ++--- .../Repositories/MixRepoDbRepository.cs | 66 +++++++++---------- .../ViewModels/MixDatabaseColumnViewModel.cs | 6 +- .../MixDatabaseRelationshipViewModel.cs | 9 ++- .../mix.signalr.hub/Hubs/VideoCallHub.cs | 8 +-- .../Engines/Base/UploaderBase.cs | 15 ++--- .../Services/OnepayService.cs | 55 +++++++++------- .../Services/OrderService.cs | 31 ++------- .../Services/PaypalService.cs | 28 ++++---- .../Controllers/ApiEcommerceController.cs | 3 - .../Resolvers/NameFieldResolver.cs | 3 +- .../ServiceCollectionExtensions.cs | 4 +- .../Abstracts/MixPostService.cs | 2 +- .../Services/MixMetadataService.cs | 1 - 15 files changed, 114 insertions(+), 137 deletions(-) diff --git a/src/modules/mix.common/Controllers/SharedApiController.cs b/src/modules/mix.common/Controllers/SharedApiController.cs index 5564dde5a..ae8fc291f 100644 --- a/src/modules/mix.common/Controllers/SharedApiController.cs +++ b/src/modules/mix.common/Controllers/SharedApiController.cs @@ -45,7 +45,8 @@ public SharedApiController( MixCacheService cacheService, IHttpContextAccessor httpContextAccessor, MixQueueMessages mixMemoryMessageQueue, - IMixTenantService mixTenantService) + IMixTenantService mixTenantService, + IMixCmsService mixCmsService) : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) { @@ -56,6 +57,7 @@ public SharedApiController( _routeProvider = routeProvider; _applicationLifetime = applicationLifetime; _mixMemoryMessageQueue = mixMemoryMessageQueue; + _mixCmsService = mixCmsService; } #region Routes diff --git a/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs b/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs index 11c6ffb3b..8019d2684 100644 --- a/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs +++ b/src/platform/mix.mixdb/Services/RuntimeDbContextService.cs @@ -80,7 +80,7 @@ public void LoadDbContextAssembly() } } - public DbContext GetMixDatabaseDbContext() + public DbContext? GetMixDatabaseDbContext() { if (!string.IsNullOrEmpty(_databaseService.GetConnectionString(MixConstants.CONST_MIXDB_CONNECTION))) { @@ -90,10 +90,7 @@ public DbContext GetMixDatabaseDbContext() } if (_assembly != null) { - - _dbContextType = _assembly.GetType("TypedDataContext.Context.DataContext"); - _ = _dbContextType ?? throw new Exception("DataContext type not found"); - + _dbContextType = _assembly.GetType("TypedDataContext.Context.DataContext") ?? throw new Exception("DataContext type not found"); var constr = _dbContextType.GetConstructor(Type.EmptyTypes); _ = constr ?? throw new Exception("DataContext ctor not found"); var ctx = (DbContext)constr.Invoke(null); @@ -101,6 +98,7 @@ public DbContext GetMixDatabaseDbContext() return ctx; } } + return default; } @@ -139,10 +137,10 @@ public List CreateDynamicDbContext() string contextFileCode = scaffoldedModelSources.ContextFile.Code; foreach (var item in scaffoldedModelSources.AdditionalFiles) { - string name = item.Path.Substring(0, item.Path.LastIndexOf('.')); + string name = item.Path[..item.Path.LastIndexOf('.')]; if (databaseNames.Any(m => string.Equals(m, name, StringComparison.OrdinalIgnoreCase))) { - ReplaceEntityNaming(databaseNames, item, ref contextFileCode); + ReplaceEntityNaming(item, ref contextFileCode); } sourceFiles.Add(item.Code); } @@ -154,9 +152,9 @@ public List CreateDynamicDbContext() return sourceFiles; } - private void ReplaceEntityNaming(List databaseNames, ScaffoldedFile item, ref string contextFileCode) + private void ReplaceEntityNaming(ScaffoldedFile item, ref string contextFileCode) { - string name = item.Path.Substring(0, item.Path.LastIndexOf('.')); + string name = item.Path[..item.Path.LastIndexOf('.')]; string newName = name.ToLower(); contextFileCode = contextFileCode.Replace($"Entity<{name}>", $"Entity<{newName}>") .Replace($"DbSet<{name}>", $"DbSet<{newName}>"); diff --git a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs index b02cb8304..faf01b23c 100644 --- a/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs +++ b/src/platform/mix.repodb/Repositories/MixRepoDbRepository.cs @@ -127,11 +127,13 @@ public async Task> GetPagingAsync(IEnumerable> GetPagingAsync(IEnumerable queryFields, PagingRequestModel pagingRequest, IEnumerable? selectFields = null) { - List orderFields = new List() { - new OrderField(pagingRequest.SortBy ?? "Id", pagingRequest.SortDirection == SortDirection.Asc ? Order.Ascending: Order.Descending) - }; + List orderFields = new() + { + new OrderField(pagingRequest.SortBy ?? "Id", pagingRequest.SortDirection == SortDirection.Asc ? Order.Ascending: Order.Descending) + }; + var count = (int)_connection.Count(_tableName, queryFields, transaction: _dbTransaction); - int pageSize = pagingRequest.PageSize.HasValue ? pagingRequest.PageSize.Value : 100; + int pageSize = pagingRequest.PageSize ?? 100; var data = await _connection.BatchQueryAsync(_tableName, pagingRequest.PageIndex, pageSize, orderFields, queryFields, selectFields, null, commandTimeout: _settings.CommandTimeout, transaction: _dbTransaction); return new PagingResponseModel() @@ -572,22 +574,20 @@ private void BeginTransaction() } } - - private IEnumerable? ParseQuery(JObject query) - { - List? result = null; - if (query != null) - { - result = new List(); - foreach (var item in query.Properties()) - { - QueryField field = new QueryField(item.Name, query.Value(item.Name)); - result.Add(field); - } - } - return result; - } - + //private IEnumerable? ParseQuery(JObject query) + //{ + // List? result = null; + // if (query != null) + // { + // result = new List(); + // foreach (var item in query.Properties()) + // { + // QueryField field = new QueryField(item.Name, query.Value(item.Name)); + // result.Add(field); + // } + // } + // return result; + //} private void InitializeRepoDb() { @@ -674,8 +674,8 @@ public void SetDbConnection(UnitOfWorkInfo dbUow) if (_isRoot || DatabaseProvider == MixDatabaseProvider.SQLITE) { - _connection = Activator.CreateInstance(connectionType) as IDbConnection; - _connection!.ConnectionString = ConnectionString; + _connection = (Activator.CreateInstance(connectionType) as IDbConnection)!; + _connection.ConnectionString = ConnectionString; } else { @@ -687,23 +687,16 @@ public void SetDbConnection(UnitOfWorkInfo dbUow) static Type GetDbConnectionType(MixDatabaseProvider dbProvider) { - switch (dbProvider) + return dbProvider switch { - case MixDatabaseProvider.SQLSERVER: - return typeof(SqlConnection); - case MixDatabaseProvider.MySQL: - return typeof(MySqlConnection); - case MixDatabaseProvider.PostgreSQL: - return typeof(NpgsqlConnection); - case MixDatabaseProvider.SQLITE: - return typeof(SqliteConnection); - default: - return typeof(SqliteConnection); - } + MixDatabaseProvider.SQLSERVER => typeof(SqlConnection), + MixDatabaseProvider.MySQL => typeof(MySqlConnection), + MixDatabaseProvider.PostgreSQL => typeof(NpgsqlConnection), + MixDatabaseProvider.SQLITE => typeof(SqliteConnection), + _ => typeof(SqliteConnection), + }; } - - #endregion public void CompleteTransaction() { @@ -720,6 +713,7 @@ public void RollbackTransaction() _dbTransaction.Rollback(); } } + public void Dispose() { if (_connection != null) diff --git a/src/platform/mix.repodb/ViewModels/MixDatabaseColumnViewModel.cs b/src/platform/mix.repodb/ViewModels/MixDatabaseColumnViewModel.cs index ba8a2330a..70dc9e4ea 100644 --- a/src/platform/mix.repodb/ViewModels/MixDatabaseColumnViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/MixDatabaseColumnViewModel.cs @@ -36,7 +36,7 @@ public MixDatabaseColumnViewModel(UnitOfWorkInfo? unitOfWorkInfo) : base(unitOfW { } - public MixDatabaseColumnViewModel(MixDatabaseColumn entity, UnitOfWorkInfo? uowInfo = null): base(entity, uowInfo) + public MixDatabaseColumnViewModel(MixDatabaseColumn entity, UnitOfWorkInfo? uowInfo = null) : base(entity, uowInfo) { } #endregion @@ -57,9 +57,7 @@ public override void ParseView(TSource sourceObject, CancellationToken { cancellationToken.ThrowIfCancellationRequested(); base.ParseView(sourceObject, cancellationToken); - ColumnConfigurations ??= Configurations != null - ? Configurations.ToObject() - : new(); + ColumnConfigurations = Configurations != null ? Configurations.ToObject()! : new(); ColumnConfigurations.Editor ??= DataType.ToString(); } diff --git a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs index 996d85107..bfc76f67d 100644 --- a/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs +++ b/src/platform/mix.repodb/ViewModels/MixDatabaseRelationshipViewModel.cs @@ -95,9 +95,14 @@ protected override async Task SaveEntityRelationshipAsync(MixDatabaseRelationshi protected override async Task DeleteHandlerAsync(CancellationToken cancellationToken = default) { - var leftDb = Context.MixDatabase.Find(ParentId); + var leftDb = await Context.MixDatabase.FindAsync(new object?[] { ParentId }, cancellationToken: cancellationToken); + var rightDb = await Context.MixDatabase.FindAsync(new object?[] { ChildId }, cancellationToken: cancellationToken); + if (leftDb is null || rightDb is null) + { + return; + } + string leftColName = $"{leftDb.SystemName}Id"; - var rightDb = Context.MixDatabase.Find(ChildId); string rightColName = $"{rightDb.SystemName}Id"; await MixDatabaseColumnViewModel.GetRepository(UowInfo, CacheService) .DeleteManyAsync(m => diff --git a/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs b/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs index 3d7298228..1cd77717d 100644 --- a/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs +++ b/src/platform/mix.signalr.hub/Hubs/VideoCallHub.cs @@ -16,9 +16,9 @@ public class VideoCallHub : BaseSignalRHub // incomingCall(User callingUser) // receiveSignal(User signalingUser, string signal) - private static readonly List Users = new List(); - private static readonly List UserCalls = new List(); - private static readonly List CallOffers = new List(); + private static readonly List Users = new(); + private static readonly List UserCalls = new(); + private static readonly List CallOffers = new(); public VideoCallHub(IAuditLogService auditLogService) : base(auditLogService) { @@ -58,7 +58,7 @@ public async Task CallUser(string targetConnectionId) var targetUser = Users.SingleOrDefault(u => u.ConnectionId == targetConnectionId); // Make sure the person we are trying to call is still here - if (targetUser == null) + if (targetUser == null || callingUser == null) { // If not, let the caller know await Clients.Caller.SendAsync("callDeclined", targetConnectionId, "The user you called has left."); diff --git a/src/platform/mix.storage.lib/Engines/Base/UploaderBase.cs b/src/platform/mix.storage.lib/Engines/Base/UploaderBase.cs index e3b36f4b4..6611338a2 100644 --- a/src/platform/mix.storage.lib/Engines/Base/UploaderBase.cs +++ b/src/platform/mix.storage.lib/Engines/Base/UploaderBase.cs @@ -16,10 +16,7 @@ protected MixTenantSystemModel CurrentTenant { get { - if (_currentTenant == null) - { - _currentTenant = Session.Get(MixRequestQueryKeywords.Tenant); - } + _currentTenant ??= Session.Get(MixRequestQueryKeywords.Tenant); return _currentTenant; } } @@ -28,24 +25,24 @@ protected UploaderBase(IHttpContextAccessor httpContextAccessor, IConfiguration { CmsUow = cmsUow; Configuration = configuration; - Session = httpContextAccessor?.HttpContext?.Session; + Session = httpContextAccessor?.HttpContext?.Session ?? throw new MixException(MixErrorStatus.Badrequest, "Session not found."); ; } public async Task CreateMedia(string fullname, int tenantId, string? createdBy, CancellationToken cancellationToken = default) { - string filePath = fullname.Substring(0, fullname.LastIndexOf('/')); + string filePath = fullname[..fullname.LastIndexOf('/')]; string fileFolder = CurrentTenant.Configurations.Domain != null ? filePath.Replace(CurrentTenant.Configurations.Domain, string.Empty) : filePath; - string fileName = fullname.Substring(fullname.LastIndexOf('/') + 1); + string fileName = fullname[(fullname.LastIndexOf('/') + 1)..]; var media = new MixMediaViewModel(CmsUow) { Id = Guid.NewGuid(), DisplayName = fileName, Status = MixContentStatus.Published, FileFolder = fileFolder, - FileName = fileName.Substring(0, fileName.LastIndexOf('.')), - Extension = fileName.Substring(fileName.LastIndexOf('.')), + FileName = fileName[..fileName.LastIndexOf('.')], + Extension = fileName[fileName.LastIndexOf('.')..], TargetUrl = fullname, CreatedBy = createdBy, MixTenantId = tenantId, diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs index dcbf1611b..65f889cb7 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Services/OnepayService.cs @@ -46,14 +46,16 @@ public OnepayService( { try { - OnepayRequest request = new OnepayRequest(order); - request.vpc_Merchant = Settings.Merchant; - request.vpc_AccessCode = Settings.AccessCode; - request.vpc_Locale = order.Currency == "VND" ? "vn" : "us"; - request.vpc_Currency = order.Currency; - request.vpc_TicketNo = HttpContextAccessor.HttpContext!.Connection.RemoteIpAddress?.ToString();//"14.241.244.43";// - request.AgainLink = $"{againUrl.TrimEnd('/')}?orderId={order.Id}"; - request.vpc_ReturnURL = returnUrl; + OnepayRequest request = new(order) + { + vpc_Merchant = Settings.Merchant, + vpc_AccessCode = Settings.AccessCode, + vpc_Locale = order.Currency == "VND" ? "vn" : "us", + vpc_Currency = order.Currency, + vpc_TicketNo = HttpContextAccessor.HttpContext!.Connection.RemoteIpAddress?.ToString(),//"14.241.244.43";// + AgainLink = $"{againUrl.TrimEnd('/')}?orderId={order.Id}", + vpc_ReturnURL = returnUrl + }; //request.vpc_CallbackURL = returnUrl; await SaveRequest(request, OrderStatus.WAITING_FOR_PAYMENT, cancellationToken); @@ -84,7 +86,7 @@ public string CreateSHA256Signature(Dictionary parameters) } // Build string from collection in preperation to be hashed - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var kvp in parameters) { if (!string.IsNullOrEmpty(kvp.Value) && kvp.Key != "vpc_SecureHash" && (kvp.Key.StartsWith("vpc_") || kvp.Key.StartsWith("user_"))) @@ -95,7 +97,7 @@ public string CreateSHA256Signature(Dictionary parameters) sb.Remove(sb.Length - 1, 1); // Create secureHash on string string hexHash = ""; - using (HMACSHA256 hasher = new HMACSHA256(convertedHash)) + using (HMACSHA256 hasher = new(convertedHash)) { byte[] hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));//(tmp)); // foreach (byte b in hashValue) @@ -108,14 +110,17 @@ public string CreateSHA256Signature(Dictionary parameters) private async Task SaveResponse(OnepayTransactionResponse response, PaymentStatus paymentStatus, CancellationToken cancellationToken) { - var vm = new OnepayTransactionResponseViewModel(response, _cmsUow); - vm.PaymentStatus = paymentStatus; + var vm = new OnepayTransactionResponseViewModel(response, _cmsUow) + { + PaymentStatus = paymentStatus + }; + await vm.SaveAsync(cancellationToken); } private async Task SaveRequest(OnepayRequest request, OrderStatus paymentStatus, CancellationToken cancellationToken) { - var vm = await OnepayTransactionRequestViewModel.GetRepository(_cmsUow, CacheService).GetSingleAsync(m => m.vpc_OrderInfo == request.vpc_OrderInfo); + var vm = await OnepayTransactionRequestViewModel.GetRepository(_cmsUow, CacheService).GetSingleAsync(m => m.vpc_OrderInfo == request.vpc_OrderInfo, cancellationToken); if (vm == null) { OnepayTransactionRequest onepayRequest = new(); @@ -127,7 +132,7 @@ private async Task SaveRequest(OnepayRequest request, OrderStatus paymentStatus, await vm.SaveAsync(cancellationToken); } - public async Task Query(OnepayQueryRequest request, CancellationToken cancellationToken) + public async Task Query(OnepayQueryRequest request) { try { @@ -148,10 +153,9 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta { cancellationToken.ThrowIfCancellationRequested(); + var response = responseObj.ToObject() ?? throw new MixException(MixErrorStatus.Badrequest, "Cannot convert response."); - var response = responseObj.ToObject(); var paymentStatus = PaymentStatus.SUCCESS; - if (!response.vpc_TxnResponseCode.Equals("0") && !string.IsNullOrEmpty(response.vpc_Message)) { if (!string.IsNullOrEmpty(response.vpc_SecureHash)) @@ -187,14 +191,17 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta public Task GetPaymentRequestAsync(OrderViewModel order, string againUrl, string returnUrl, CancellationToken cancellationToken) { - OnepayRequest request = new OnepayRequest(order); - request.vpc_Merchant = Settings.Merchant; - request.vpc_AccessCode = Settings.AccessCode; - request.vpc_Locale = order.Currency == "VND"? "vn": "us"; - request.vpc_Currency = order.Currency; - request.vpc_TicketNo = HttpContextAccessor.HttpContext!.Connection.RemoteIpAddress?.ToString();//"14.241.244.43";// - request.AgainLink = $"{againUrl.TrimEnd('/')}?orderId={order.ExternalId}"; - request.vpc_ReturnURL = returnUrl; + OnepayRequest request = new(order) + { + vpc_Merchant = Settings.Merchant, + vpc_AccessCode = Settings.AccessCode, + vpc_Locale = order.Currency == "VND" ? "vn" : "us", + vpc_Currency = order.Currency, + vpc_TicketNo = HttpContextAccessor.HttpContext!.Connection.RemoteIpAddress?.ToString(),//"14.241.244.43";// + AgainLink = $"{againUrl.TrimEnd('/')}?orderId={order.ExternalId}", + vpc_ReturnURL = returnUrl + }; + //request.vpc_CallbackURL = returnUrl; return Task.FromResult(ReflectionHelper.ParseObject(request)); } diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs index ccbfaeeb6..bbbf63404 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Services/OrderService.cs @@ -22,8 +22,6 @@ public class OrderService : TenantServiceBase, IOrderService { private readonly TenantUserManager _userManager; private readonly UnitOfWorkInfo _uow; - private double _exchangeRate = 1; - private readonly MixConfigurationService _configService; public OrderService( IHttpContextAccessor httpContextAccessor, UnitOfWorkInfo uow, @@ -34,8 +32,6 @@ public OrderService( { _uow = uow; _userManager = userManager; - _configService = configService; - _exchangeRate = _configService.Configs.FirstOrDefault(m => m.SystemName == "exchangeRate")?.GetValue() ?? 1; } public async Task> GetUserOrders( @@ -43,12 +39,7 @@ public async Task> GetUserOrders( FilterOrderDto request, CancellationToken cancellationToken = default) { - var user = await _userManager.GetUserAsync(principal); - - if (user == null) - { - throw new MixException(MixErrorStatus.UnAuthorized); - } + var user = await _userManager.GetUserAsync(principal) ?? throw new MixException(MixErrorStatus.UnAuthorized); var searchRequest = new SearchQueryModel( HttpContextAccessor.HttpContext!.Request, request, @@ -68,17 +59,11 @@ public async Task GetUserOrder(ClaimsPrincipal principal, int or { cancellationToken.ThrowIfCancellationRequested(); - var user = await _userManager.GetUserAsync(principal); - - if (user == null) - { - throw new MixException(MixErrorStatus.UnAuthorized); - } - + var user = await _userManager.GetUserAsync(principal) ?? throw new MixException(MixErrorStatus.UnAuthorized); var result = await OrderViewModel.GetRepository(_uow, CacheService).GetSingleAsync(m => m.Id == orderId && m.UserId == user.Id, cancellationToken); return result; } - + public async Task GetGuestOrder(int orderId, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -93,14 +78,8 @@ public async Task CancelOrder( { cancellationToken.ThrowIfCancellationRequested(); - var user = await _userManager.GetUserAsync(principal); - - var order = await OrderViewModel.GetRepository(_uow, CacheService).GetSingleAsync(m => m.Id == id && m.UserId == user!.Id, cancellationToken); - if (order == null) - { - throw new MixException(MixErrorStatus.Badrequest, "Invalid Order"); - } - + var user = await _userManager.GetUserAsync(principal) ?? throw new MixException(MixErrorStatus.Badrequest, "User not found"); + var order = await OrderViewModel.GetRepository(_uow, CacheService).GetSingleAsync(m => m.Id == id && m.UserId == user!.Id, cancellationToken) ?? throw new MixException(MixErrorStatus.Badrequest, "Invalid Order"); if (order.PaymentStatus == PaymentStatus.SUCCESS) { throw new MixException(MixErrorStatus.Badrequest, "Cannot cancel paid order"); diff --git a/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs b/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs index 4965d888c..c8c4f0c94 100644 --- a/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs +++ b/src/services/ecommerces/mix.services.ecommerce.lib/Services/PaypalService.cs @@ -31,8 +31,8 @@ public sealed class PaypalService : TenantServiceBase, IPaymentService { private readonly UnitOfWorkInfo _cmsUow; private readonly HttpClient _httpClient; - private PaypalConfigurations _settings { get; set; } = new PaypalConfigurations(); - public PayPalAccessToken? Token { get => GetPayPalAccessTokenAsync(); } + private PaypalConfigurations Settings { get; set; } = new PaypalConfigurations(); + public PayPalAccessToken Token { get => GetPayPalAccessTokenAsync() ?? throw new MixException(MixErrorStatus.Badrequest, "Cannot get token"); } public PaypalService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -42,7 +42,7 @@ public PaypalService( : base(httpContextAccessor, cacheService, mixTenantService) { var session = configuration.GetSection(MixAppSettingsSection.Payments).GetSection("Paypal"); - session.Bind(_settings); + session.Bind(Settings); _cmsUow = cmsUow; _httpClient = GetPaypalHttpClient(); } @@ -112,8 +112,10 @@ public async Task ProcessPaymentResponse(OrderViewModel orderDeta private async Task SaveResponse(PaypalOrderCapturedResponse? response, PaymentStatus paymentStatus, CancellationToken cancellationToken) { var resp = new PaypalTransactionResponse(response!); - var vm = new PaypalTransactionResponseViewModel(resp, _cmsUow); - vm.PaymentStatus = paymentStatus; + var vm = new PaypalTransactionResponseViewModel(resp, _cmsUow) + { + PaymentStatus = paymentStatus + }; await vm.SaveAsync(cancellationToken); } @@ -128,7 +130,7 @@ private HttpClient GetPaypalHttpClient() { var http = new HttpClient { - BaseAddress = new Uri(_settings.BaseUrl), + BaseAddress = new Uri(Settings.BaseUrl), Timeout = TimeSpan.FromSeconds(30), }; @@ -137,12 +139,12 @@ private HttpClient GetPaypalHttpClient() private PayPalAccessToken? GetPayPalAccessTokenAsync() { - var clientId = _settings.ClientId; - var secret = _settings.SecretKey; + var clientId = Settings.ClientId; + var secret = Settings.SecretKey; byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes($"{clientId}:{secret}"); - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/v1/oauth2/token"); + HttpRequestMessage request = new(HttpMethod.Post, "/v1/oauth2/token"); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes)); var form = new Dictionary @@ -162,7 +164,7 @@ private HttpClient GetPaypalHttpClient() OrderViewModel order, string againUrl, string returnUrl, CancellationToken cancellationToken = default) { - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v2/checkout/orders"); + HttpRequestMessage request = new(HttpMethod.Post, "v2/checkout/orders"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token); var payment = await GetPaymentRequestAsync(order, againUrl, returnUrl, cancellationToken); @@ -170,7 +172,7 @@ private HttpClient GetPaypalHttpClient() HttpResponseMessage response = await SendPaypalRequest(request); - string content = await response.Content.ReadAsStringAsync(); + string content = await response.Content.ReadAsStringAsync(cancellationToken); if (response.IsSuccessStatusCode) { PaypalOrderCreatedResponse? paypalPaymentCreated = JsonConvert.DeserializeObject(content); @@ -182,7 +184,7 @@ private HttpClient GetPaypalHttpClient() private async Task CaptureOrderResult(string? orderId) { - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"v2/checkout/orders/{orderId}/capture"); + HttpRequestMessage request = new(HttpMethod.Post, $"v2/checkout/orders/{orderId}/capture"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token); request.Content = new StringContent("", Encoding.Default, "application/json"); HttpResponseMessage response = await SendPaypalRequest(request); @@ -194,7 +196,7 @@ private HttpClient GetPaypalHttpClient() private async Task GetOrderResult(string? orderId) { - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"v2/checkout/orders/{orderId}"); + HttpRequestMessage request = new(HttpMethod.Get, $"v2/checkout/orders/{orderId}"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token); request.Content = new StringContent("", Encoding.Default, "application/json"); HttpResponseMessage response = await SendPaypalRequest(request); diff --git a/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs b/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs index 41d2f49b3..cbd0211cc 100644 --- a/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs +++ b/src/services/ecommerces/mix.services.ecommerce/Controllers/ApiEcommerceController.cs @@ -28,7 +28,6 @@ namespace Mix.Services.ecommerce.Controllers public class ApiEcommerceController : MixTenantApiControllerBase { private readonly PaymentConfigurationModel _paymentConfiguration = new(); - private readonly IPortalHubClientService _portalHub; private readonly IEcommerceService _ecommerceService; private readonly IOrderService _orderService; protected UnitOfWorkInfo CmsUow; @@ -43,7 +42,6 @@ public ApiEcommerceController( IEcommerceService ecommerceService, UnitOfWorkInfo cmsUow, IOrderService orderService, - IPortalHubClientService portalHub, IMixTenantService mixTenantService) : base(httpContextAccessor, configuration, cacheService, translator, mixIdentityService, queueService, mixTenantService) @@ -53,7 +51,6 @@ public ApiEcommerceController( _orderService = orderService; var session = configuration.GetSection(MixAppSettingsSection.Payments); session.Bind(_paymentConfiguration); - _portalHub = portalHub; } #region Routes diff --git a/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs b/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs index d4fb483c4..9c8474ffc 100644 --- a/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs +++ b/src/services/graphql/mix.services.graphql.lib/Resolvers/NameFieldResolver.cs @@ -11,12 +11,11 @@ namespace Mix.Services.Graphql.Lib.Resolvers { public class NameFieldResolver : IFieldResolver { - private static object GetPropValue(object src, string propName) + private static object? GetPropValue(object src, string propName) { return src.GetType().GetProperty(propName)?.GetValue(src, null); } - public async ValueTask ResolveAsync(IResolveFieldContext context) { var source = context.Source; diff --git a/src/services/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs b/src/services/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs index befe9721f..9d7d05497 100644 --- a/src/services/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs +++ b/src/services/graphql/mix.services.graphql.lib/ServiceCollectionExtensions.cs @@ -29,9 +29,9 @@ public static IServiceCollection AddMixGraphQL(this IServiceCollection services) services.TryAddSingleton((resolver) => { var runtimeDbContextService = resolver.GetRequiredService(); - var dbContext = runtimeDbContextService.GetMixDatabaseDbContext(); + var dbContext = runtimeDbContextService.GetMixDatabaseDbContext()!; var tableNameLookup = resolver.GetRequiredService(); - DatabaseMetadata metaDatabase = new DatabaseMetadata(dbContext, tableNameLookup); + DatabaseMetadata metaDatabase = new(dbContext, tableNameLookup); var schema = new Schema { Query = new GraphQLQuery(dbContext, metaDatabase, tableNameLookup) }; return schema; }); diff --git a/src/services/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs b/src/services/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs index 714c1775a..47c688d04 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Abstracts/MixPostService.cs @@ -69,7 +69,7 @@ public virtual async Task> SearchPosts(SearchPostQuer } } - public IQueryable ParseMetadataQueriesPredicate(List MetadataQueries) + public IQueryable? ParseMetadataQueriesPredicate(List MetadataQueries) { IQueryable? allowedIdQuery = MetadataService.GetQueryableContentIdByMetadataSeoContent( MetadataQueries, MixContentType.Post); diff --git a/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs b/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs index c44beb28b..a35b63993 100644 --- a/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs +++ b/src/services/mix-databases/mix.services.databases.lib/Services/MixMetadataService.cs @@ -30,7 +30,6 @@ public MixMetadataService( IHttpContextAccessor httpContextAccessor, UnitOfWorkInfo uow, MixIdentityService identityService, - UnitOfWorkInfo cmsUow, MixCacheService cacheService, IMixTenantService mixTenantService) : base(httpContextAccessor, cacheService, mixTenantService) From 0c2822940cc44b4421c0e68194fff4cb31cacb52 Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 08:48:48 +0700 Subject: [PATCH 4/7] Update heart --- src/platform/core/mix-heart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/core/mix-heart b/src/platform/core/mix-heart index 54ce82d2d..10c53e1dd 160000 --- a/src/platform/core/mix-heart +++ b/src/platform/core/mix-heart @@ -1 +1 @@ -Subproject commit 54ce82d2d0625e803c4a51e22393a4fd16b848ad +Subproject commit 10c53e1dd3d33f7d167f104fa8c1e3ed18187df9 From 5d69074f83082e9317f6283e1934e82e9ed5a658 Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 22:14:05 +0700 Subject: [PATCH 5/7] Fix initial home page --- src/platform/mix.service/Services/MixPermissionService.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/platform/mix.service/Services/MixPermissionService.cs b/src/platform/mix.service/Services/MixPermissionService.cs index 685ed9c35..bf60493a4 100644 --- a/src/platform/mix.service/Services/MixPermissionService.cs +++ b/src/platform/mix.service/Services/MixPermissionService.cs @@ -31,7 +31,7 @@ public async Task Reload() { if (!GlobalConfigService.Instance.IsInit) { - UnitOfWorkInfo uow = new(new MixDbDbContext(_databaseService)); ; + UnitOfWorkInfo uow = new(new MixDbDbContext(_databaseService)); try { RoleEndpoints = new Dictionary(); @@ -49,6 +49,8 @@ public async Task Reload() && m.ChildDatabaseName == MixDatabaseNames.SYSTEM_PERMISSION_ENDPOINT && permissionIds.Contains(m.ParentId)) .Select(m => m.ChildId); + + // TODO: PermissionEndpoint cannot initial at first time var endpoints = await uow.DbContext.PermissionEndpoint.Where( m => endpointIds.Contains(m.Id) && !string.IsNullOrEmpty(m.Path) @@ -73,6 +75,9 @@ public async Task Reload() } } + } + catch (Exception ex) + { } finally { From 97786d3feed66f4d31aee57d654378fe3d09c694 Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 22:15:04 +0700 Subject: [PATCH 6/7] update heart --- src/platform/core/mix-heart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/core/mix-heart b/src/platform/core/mix-heart index 10c53e1dd..0fab385aa 160000 --- a/src/platform/core/mix-heart +++ b/src/platform/core/mix-heart @@ -1 +1 @@ -Subproject commit 10c53e1dd3d33f7d167f104fa8c1e3ed18187df9 +Subproject commit 0fab385aa377f1d97836978796538387fd5e2976 From a42eb3c1139d30807c4bc3008667e3e284a78748 Mon Sep 17 00:00:00 2001 From: Phat Date: Sun, 3 Sep 2023 22:34:19 +0700 Subject: [PATCH 7/7] Fix audit log --- src/platform/mix.log/ViewModels/AuditLogViewModel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/mix.log/ViewModels/AuditLogViewModel.cs b/src/platform/mix.log/ViewModels/AuditLogViewModel.cs index 8c89ed702..56fa21fb3 100644 --- a/src/platform/mix.log/ViewModels/AuditLogViewModel.cs +++ b/src/platform/mix.log/ViewModels/AuditLogViewModel.cs @@ -25,7 +25,7 @@ public AuditLogViewModel() { } - public AuditLogViewModel(AuditLog entity, UnitOfWorkInfo? uowInfo) + public AuditLogViewModel(AuditLog entity, UnitOfWorkInfo uowInfo) : base(entity, uowInfo) { }