From ab3f0853a743d5c33dd07bcf6cdb13a5f404ad56 Mon Sep 17 00:00:00 2001 From: Pavel Vesely Date: Sat, 14 Mar 2020 21:52:26 +0100 Subject: [PATCH 1/3] Naming conventions --- .../Modules/Admin/Modules/Settings.razor | 2 + Oqtane.Client/Modules/Admin/Pages/Index.razor | 10 +- .../Modules/Admin/Profiles/Edit.razor | 86 ++++++------- .../Modules/Admin/Profiles/Index.razor | 18 +-- .../Modules/Admin/RecycleBin/Index.razor | 60 ++++----- .../Modules/Admin/Register/Index.razor | 56 ++++---- Oqtane.Client/Modules/Admin/Roles/Add.razor | 2 +- Oqtane.Client/Modules/Admin/Roles/Edit.razor | 42 +++--- Oqtane.Client/Modules/Admin/Roles/Index.razor | 18 +-- Oqtane.Client/Modules/Admin/Site/Index.razor | 2 +- Oqtane.Client/Modules/Admin/Sites/Add.razor | 120 +++++++++--------- Oqtane.Client/UI/SiteRouter.razor | 2 + Oqtane.Client/UI/ThemeBuilder.razor | 2 +- Oqtane.Server/Controllers/AliasController.cs | 22 ++-- Oqtane.Server/Controllers/FileController.cs | 72 ++++++----- 15 files changed, 267 insertions(+), 247 deletions(-) diff --git a/Oqtane.Client/Modules/Admin/Modules/Settings.razor b/Oqtane.Client/Modules/Admin/Modules/Settings.razor index 86ddb41b..ae515412 100644 --- a/Oqtane.Client/Modules/Admin/Modules/Settings.razor +++ b/Oqtane.Client/Modules/Admin/Modules/Settings.razor @@ -70,7 +70,9 @@ string _permissions; string _pageId; +#pragma warning disable 649 PermissionGrid _permissionGrid; +#pragma warning restore 649 RenderFragment DynamicComponent { get; set; } object _settings; diff --git a/Oqtane.Client/Modules/Admin/Pages/Index.razor b/Oqtane.Client/Modules/Admin/Pages/Index.razor index 85f9f12f..ce546547 100644 --- a/Oqtane.Client/Modules/Admin/Pages/Index.razor +++ b/Oqtane.Client/Modules/Admin/Pages/Index.razor @@ -24,18 +24,18 @@ @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - private async Task DeletePage(Page Page) + private async Task DeletePage(Page page) { try { - Page.IsDeleted = true; - await PageService.UpdatePageAsync(Page); - await logger.LogInformation("Page Deleted {Page}", Page); + page.IsDeleted = true; + await PageService.UpdatePageAsync(page); + await logger.LogInformation("Page Deleted {Page}", page); NavigationManager.NavigateTo(NavigateUrl("admin/pages")); } catch (Exception ex) { - await logger.LogError(ex, "Error Deleting Page {Page} {Error}", Page, ex.Message); + await logger.LogError(ex, "Error Deleting Page {Page} {Error}", page, ex.Message); AddModuleMessage("Error Deleting Page", MessageType.Error); } } diff --git a/Oqtane.Client/Modules/Admin/Profiles/Edit.razor b/Oqtane.Client/Modules/Admin/Profiles/Edit.razor index dfdbe432..bfba2d25 100644 --- a/Oqtane.Client/Modules/Admin/Profiles/Edit.razor +++ b/Oqtane.Client/Modules/Admin/Profiles/Edit.razor @@ -9,7 +9,7 @@ - + @@ -17,7 +17,7 @@ - + @@ -25,7 +25,7 @@ - @@ -33,7 +33,7 @@ - + @@ -41,7 +41,7 @@ - + @@ -49,7 +49,7 @@ - + @@ -57,7 +57,7 @@ - + @@ -65,7 +65,7 @@ - @@ -76,7 +76,7 @@ - @@ -90,16 +90,16 @@ public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } public override string Actions { get { return "Add,Edit"; } } - int profileid = -1; - string name = ""; - string title = ""; - string description = ""; - string category = ""; - string vieworder = "0"; - string maxlength = "0"; - string defaultvalue = ""; - string isrequired = "False"; - string isprivate = "False"; + int _profileid = -1; + string _name = ""; + string _title = ""; + string _description = ""; + string _category = ""; + string _vieworder = "0"; + string _maxlength = "0"; + string _defaultvalue = ""; + string _isrequired = "False"; + string _isprivate = "False"; protected override async Task OnInitializedAsync() { @@ -107,25 +107,25 @@ { if (PageState.QueryString.ContainsKey("id")) { - profileid = Int32.Parse(PageState.QueryString["id"]); - Profile profile = await ProfileService.GetProfileAsync(profileid); + _profileid = Int32.Parse(PageState.QueryString["id"]); + Profile profile = await ProfileService.GetProfileAsync(_profileid); if (profile != null) { - name = profile.Name; - title = profile.Title; - description = profile.Description; - category = profile.Category; - vieworder = profile.ViewOrder.ToString(); - maxlength = profile.MaxLength.ToString(); - defaultvalue = profile.DefaultValue; - isrequired = profile.IsRequired.ToString(); - isprivate = profile.IsPrivate.ToString(); + _name = profile.Name; + _title = profile.Title; + _description = profile.Description; + _category = profile.Category; + _vieworder = profile.ViewOrder.ToString(); + _maxlength = profile.MaxLength.ToString(); + _defaultvalue = profile.DefaultValue; + _isrequired = profile.IsRequired.ToString(); + _isprivate = profile.IsPrivate.ToString(); } } } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Profile {ProfileId} {Error}", profileid, ex.Message); + await logger.LogError(ex, "Error Loading Profile {ProfileId} {Error}", _profileid, ex.Message); AddModuleMessage("Error Loading Profile", MessageType.Error); } } @@ -135,30 +135,30 @@ try { Profile profile; - if (profileid != -1) + if (_profileid != -1) { - profile = await ProfileService.GetProfileAsync(profileid); + profile = await ProfileService.GetProfileAsync(_profileid); } else { profile = new Profile(); } - profile.Name = name; - profile.Title = title; - profile.Description = description; - profile.Category = category; - profile.ViewOrder = int.Parse(vieworder); - profile.MaxLength = int.Parse(maxlength); - profile.DefaultValue = defaultvalue; - profile.IsRequired = (isrequired == null ? false : Boolean.Parse(isrequired)); - profile.IsPrivate = (isprivate == null ? false : Boolean.Parse(isprivate)); + profile.Name = _name; + profile.Title = _title; + profile.Description = _description; + profile.Category = _category; + profile.ViewOrder = int.Parse(_vieworder); + profile.MaxLength = int.Parse(_maxlength); + profile.DefaultValue = _defaultvalue; + profile.IsRequired = (_isrequired == null ? false : Boolean.Parse(_isrequired)); + profile.IsPrivate = (_isprivate == null ? false : Boolean.Parse(_isprivate)); profile = await ProfileService.UpdateProfileAsync(profile); await logger.LogInformation("Profile Saved {Profile}", profile); NavigationManager.NavigateTo(NavigateUrl()); } catch (Exception ex) { - await logger.LogError(ex, "Error Saving Profile {ProfleId} {Error}", profileid, ex.Message); + await logger.LogError(ex, "Error Saving Profile {ProfleId} {Error}", _profileid, ex.Message); AddModuleMessage("Error Saving Profile", MessageType.Error); } } diff --git a/Oqtane.Client/Modules/Admin/Profiles/Index.razor b/Oqtane.Client/Modules/Admin/Profiles/Index.razor index b362895a..593ccca4 100644 --- a/Oqtane.Client/Modules/Admin/Profiles/Index.razor +++ b/Oqtane.Client/Modules/Admin/Profiles/Index.razor @@ -2,7 +2,7 @@ @inherits ModuleBase @inject IProfileService ProfileService -@if (Profiles == null) +@if (_profiles == null) {

Loading...

} @@ -10,7 +10,7 @@ else { - +
    @@ -27,25 +27,25 @@ else @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - List Profiles; + List _profiles; protected override async Task OnInitializedAsync() { - Profiles = await ProfileService.GetProfilesAsync(PageState.Site.SiteId); + _profiles = await ProfileService.GetProfilesAsync(PageState.Site.SiteId); } - private async Task DeleteProfile(int ProfileId) + private async Task DeleteProfile(int profileId) { try { - await ProfileService.DeleteProfileAsync(ProfileId); - await logger.LogInformation("Profile Deleted {ProfileId}", ProfileId); + await ProfileService.DeleteProfileAsync(profileId); + await logger.LogInformation("Profile Deleted {ProfileId}", profileId); AddModuleMessage("Profile Deleted", MessageType.Success); } catch (Exception ex) { - await logger.LogError(ex, "Error Deleting Profile {ProfileId} {Error}", ProfileId, ex.Message); + await logger.LogError(ex, "Error Deleting Profile {ProfileId} {Error}", profileId, ex.Message); AddModuleMessage("Error Deleting Profile", MessageType.Error); } } -} \ No newline at end of file +} diff --git a/Oqtane.Client/Modules/Admin/RecycleBin/Index.razor b/Oqtane.Client/Modules/Admin/RecycleBin/Index.razor index 72409259..012a5495 100644 --- a/Oqtane.Client/Modules/Admin/RecycleBin/Index.razor +++ b/Oqtane.Client/Modules/Admin/RecycleBin/Index.razor @@ -23,14 +23,14 @@
- @if (pages == null) + @if (_pages == null) {

No Deleted Pages

} else { - +
    @@ -49,14 +49,14 @@ }
- @if (modules == null) + @if (_modules == null) {

No Deleted Modules

} else { - +
    @@ -83,8 +83,8 @@ @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - List pages; - List modules; + List _pages; + List _modules; protected override async Task OnInitializedAsync() { @@ -101,84 +101,84 @@ private async Task Load() { - pages = await PageService.GetPagesAsync(PageState.Site.SiteId); - pages = pages.Where(item => item.IsDeleted).ToList(); + _pages = await PageService.GetPagesAsync(PageState.Site.SiteId); + _pages = _pages.Where(item => item.IsDeleted).ToList(); - modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId); - modules = modules.Where(item => item.IsDeleted).ToList(); + _modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId); + _modules = _modules.Where(item => item.IsDeleted).ToList(); } - private async Task RestorePage(Page Page) + private async Task RestorePage(Page page) { try { - Page.IsDeleted = false; - await PageService.UpdatePageAsync(Page); - await logger.LogInformation("Page Restored {Page}", Page); + page.IsDeleted = false; + await PageService.UpdatePageAsync(page); + await logger.LogInformation("Page Restored {Page}", page); await Load(); StateHasChanged(); NavigationManager.NavigateTo(NavigateUrl()); } catch (Exception ex) { - await logger.LogError(ex, "Error Restoring Deleted Page {Page} {Error}", Page, ex.Message); + await logger.LogError(ex, "Error Restoring Deleted Page {Page} {Error}", page, ex.Message); AddModuleMessage("Error Restoring Deleted Page", MessageType.Error); } } - private async Task DeletePage(Page Page) + private async Task DeletePage(Page page) { try { - await PageService.DeletePageAsync(Page.PageId); - await logger.LogInformation("Page Permanently Deleted {Page}", Page); + await PageService.DeletePageAsync(page.PageId); + await logger.LogInformation("Page Permanently Deleted {Page}", page); await Load(); StateHasChanged(); NavigationManager.NavigateTo(NavigateUrl()); } catch (Exception ex) { - await logger.LogError(ex, "Error Permanently Deleting Page {Page} {Error}", Page, ex.Message); + await logger.LogError(ex, "Error Permanently Deleting Page {Page} {Error}", page, ex.Message); AddModuleMessage(ex.Message, MessageType.Error); } } - private async Task RestoreModule(Module Module) + private async Task RestoreModule(Module module) { try { - PageModule pagemodule = await PageModuleService.GetPageModuleAsync(Module.PageModuleId); + PageModule pagemodule = await PageModuleService.GetPageModuleAsync(module.PageModuleId); pagemodule.IsDeleted = false; await PageModuleService.UpdatePageModuleAsync(pagemodule); - await logger.LogInformation("Module Restored {Module}", Module); + await logger.LogInformation("Module Restored {Module}", module); await Load(); StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Restoring Deleted Module {Module} {Error}", Module, ex.Message); + await logger.LogError(ex, "Error Restoring Deleted Module {Module} {Error}", module, ex.Message); AddModuleMessage("Error Restoring Deleted Module", MessageType.Error); } } - private async Task DeleteModule(Module Module) + private async Task DeleteModule(Module module) { try { - await PageModuleService.DeletePageModuleAsync(Module.PageModuleId); + await PageModuleService.DeletePageModuleAsync(module.PageModuleId); // check if there are any remaining module instances in the site - modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId); - if (!modules.Exists(item => item.ModuleId == Module.ModuleId)) + _modules = await ModuleService.GetModulesAsync(PageState.Site.SiteId); + if (!_modules.Exists(item => item.ModuleId == module.ModuleId)) { - await ModuleService.DeleteModuleAsync(Module.ModuleId); + await ModuleService.DeleteModuleAsync(module.ModuleId); } - await logger.LogInformation("Module Permanently Deleted {Module}", Module); + await logger.LogInformation("Module Permanently Deleted {Module}", module); await Load(); StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Permanently Deleting Module {Module} {Error}", Module, ex.Message); + await logger.LogError(ex, "Error Permanently Deleting Module {Module} {Error}", module, ex.Message); AddModuleMessage("Error Permanently Deleting Module", MessageType.Error); } } diff --git a/Oqtane.Client/Modules/Admin/Register/Index.razor b/Oqtane.Client/Modules/Admin/Register/Index.razor index 40b59b89..46fdca01 100644 --- a/Oqtane.Client/Modules/Admin/Register/Index.razor +++ b/Oqtane.Client/Modules/Admin/Register/Index.razor @@ -3,31 +3,31 @@ @inject NavigationManager NavigationManager @inject IUserService UserService -@if (Message != "") +@if (_message != "") { - + }
- +
- +
- - + +
- - + +
- +
@@ -36,38 +36,40 @@ @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Anonymous; } } - string Message = "Please Note That Registration Requires A Valid Email Address In Order To Verify Your Identity"; - string Username = ""; - string Password = ""; - string Confirm = ""; - string Email = ""; - string DisplayName = ""; + string _message = "Please Note That Registration Requires A Valid Email Address In Order To Verify Your Identity"; + string _username = ""; + string _password = ""; + string _confirm = ""; + string _email = ""; + string _displayName = ""; private async Task Register() { try { - Message = ""; - if (Username != "" && Password != "" && Confirm != "" && Email != "") + _message = ""; + if (_username != "" && _password != "" && _confirm != "" && _email != "") { - if (Password == Confirm) + if (_password == _confirm) { - User user = new User(); - user.SiteId = PageState.Site.SiteId; - user.Username = Username; - user.DisplayName = (DisplayName == "" ? Username : DisplayName); - user.Email = Email; - user.Password = Password; + User user = new User + { + SiteId = PageState.Site.SiteId, + Username = _username, + DisplayName = (_displayName == "" ? _username : _displayName), + Email = _email, + Password = _password + }; user = await UserService.AddUserAsync(user); if (user != null) { - await logger.LogInformation("User Created {Username} {Email}", Username, Email); + await logger.LogInformation("User Created {Username} {Email}", _username, _email); AddModuleMessage("User Account Created. Please Check Your Email For Verification Instructions.", MessageType.Info); } else { - await logger.LogError("Error Adding User {Username} {Email}", Username, Email); + await logger.LogError("Error Adding User {Username} {Email}", _username, _email); AddModuleMessage("Error Adding User. Please Ensure Password Meets Complexity Requirements And Username Is Not Already In Use.", MessageType.Error); } } @@ -83,7 +85,7 @@ } catch (Exception ex) { - await logger.LogError(ex, "Error Adding User {Username} {Email} {Error}", Username, Email, ex.Message); + await logger.LogError(ex, "Error Adding User {Username} {Email} {Error}", _username, _email, ex.Message); AddModuleMessage("Error Adding User", MessageType.Error); } } diff --git a/Oqtane.Client/Modules/Admin/Roles/Add.razor b/Oqtane.Client/Modules/Admin/Roles/Add.razor index fccd1981..e908dd1c 100644 --- a/Oqtane.Client/Modules/Admin/Roles/Add.razor +++ b/Oqtane.Client/Modules/Admin/Roles/Add.razor @@ -17,7 +17,7 @@ - diff --git a/Oqtane.Client/Modules/Admin/Roles/Edit.razor b/Oqtane.Client/Modules/Admin/Roles/Edit.razor index 5d884975..71bc826a 100644 --- a/Oqtane.Client/Modules/Admin/Roles/Edit.razor +++ b/Oqtane.Client/Modules/Admin/Roles/Edit.razor @@ -9,7 +9,7 @@ - + @@ -17,7 +17,7 @@ - @@ -25,7 +25,7 @@ - @@ -36,7 +36,7 @@ - @@ -49,40 +49,40 @@ @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - int roleid; - string name = ""; - string description = ""; - string isautoassigned = "False"; - string issystem = "False"; + int _roleid; + string _name = ""; + string _description = ""; + string _isautoassigned = "False"; + string _issystem = "False"; protected override async Task OnInitializedAsync() { try { - roleid = Int32.Parse(PageState.QueryString["id"]); - Role role = await RoleService.GetRoleAsync(roleid); + _roleid = Int32.Parse(PageState.QueryString["id"]); + Role role = await RoleService.GetRoleAsync(_roleid); if (role != null) { - name = role.Name; - description = role.Description; - isautoassigned = role.IsAutoAssigned.ToString(); - issystem = role.IsSystem.ToString(); + _name = role.Name; + _description = role.Description; + _isautoassigned = role.IsAutoAssigned.ToString(); + _issystem = role.IsSystem.ToString(); } } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Role {RoleId} {Error}", roleid, ex.Message); + await logger.LogError(ex, "Error Loading Role {RoleId} {Error}", _roleid, ex.Message); AddModuleMessage("Error Loading Role", MessageType.Error); } } private async Task SaveRole() { - Role role = await RoleService.GetRoleAsync(roleid); - role.Name = name; - role.Description = description; - role.IsAutoAssigned = (isautoassigned == null ? false : Boolean.Parse(isautoassigned)); - role.IsSystem = (issystem == null ? false : Boolean.Parse(issystem)); + Role role = await RoleService.GetRoleAsync(_roleid); + role.Name = _name; + role.Description = _description; + role.IsAutoAssigned = (_isautoassigned != null && Boolean.Parse(_isautoassigned)); + role.IsSystem = (_issystem != null && Boolean.Parse(_issystem)); try { diff --git a/Oqtane.Client/Modules/Admin/Roles/Index.razor b/Oqtane.Client/Modules/Admin/Roles/Index.razor index 79124760..29378752 100644 --- a/Oqtane.Client/Modules/Admin/Roles/Index.razor +++ b/Oqtane.Client/Modules/Admin/Roles/Index.razor @@ -2,7 +2,7 @@ @inherits ModuleBase @inject IRoleService RoleService -@if (Roles == null) +@if (_roles == null) {

Loading...

} @@ -10,7 +10,7 @@ else { - +
    @@ -27,25 +27,25 @@ else @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - List Roles; + List _roles; protected override async Task OnParametersSetAsync() { - Roles = await RoleService.GetRolesAsync(PageState.Site.SiteId); + _roles = await RoleService.GetRolesAsync(PageState.Site.SiteId); } - private async Task DeleteRole(Role Role) + private async Task DeleteRole(Role role) { try { - await RoleService.DeleteRoleAsync(Role.RoleId); - await logger.LogInformation("Role Deleted {Role}", Role); + await RoleService.DeleteRoleAsync(role.RoleId); + await logger.LogInformation("Role Deleted {Role}", role); StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Deleting Role {Role} {Error}", Role, ex.Message); + await logger.LogError(ex, "Error Deleting Role {Role} {Error}", role, ex.Message); AddModuleMessage("Error Deleting Role", MessageType.Error); } } -} \ No newline at end of file +} diff --git a/Oqtane.Client/Modules/Admin/Site/Index.razor b/Oqtane.Client/Modules/Admin/Site/Index.razor index 496d411f..b3692a49 100644 --- a/Oqtane.Client/Modules/Admin/Site/Index.razor +++ b/Oqtane.Client/Modules/Admin/Site/Index.razor @@ -31,7 +31,7 @@ - diff --git a/Oqtane.Client/Modules/Admin/Sites/Add.razor b/Oqtane.Client/Modules/Admin/Sites/Add.razor index 944610d1..a692d081 100644 --- a/Oqtane.Client/Modules/Admin/Sites/Add.razor +++ b/Oqtane.Client/Modules/Admin/Sites/Add.razor @@ -7,7 +7,7 @@ @inject IThemeService ThemeService @inject IUserService UserService -@if (tenants == null) +@if (_tenants == null) {

Loading...

} @@ -21,7 +21,7 @@ else + @@ -41,7 +41,7 @@ else - @@ -51,7 +51,7 @@ else + + - @if (!isinitialized) + @if (!_isinitialized) { - + @@ -101,7 +101,7 @@ else - + } @@ -113,50 +113,50 @@ else @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Host; } } - Dictionary themes = new Dictionary(); - Dictionary panelayouts = new Dictionary(); - Dictionary containers = new Dictionary(); + Dictionary _themes = new Dictionary(); + Dictionary _panelayouts = new Dictionary(); + Dictionary _containers = new Dictionary(); - List Themes; - List tenants; - string tenantid = "-1"; - string name = ""; - string urls = ""; - string themetype = ""; - string layouttype = ""; - string containertype = ""; - bool isinitialized = true; - string username = ""; - string password = ""; + List _themeList; + List _tenants; + string _tenantid = "-1"; + string _name = ""; + string _urls = ""; + string _themetype = ""; + string _layouttype = ""; + string _containertype = ""; + bool _isinitialized = true; + string _username = ""; + string _password = ""; protected override async Task OnInitializedAsync() { - Themes = await ThemeService.GetThemesAsync(); - tenants = await TenantService.GetTenantsAsync(); - urls = PageState.Alias.Name; - themes = ThemeService.GetThemeTypes(Themes); - containers = ThemeService.GetContainerTypes(Themes); - username = Constants.HostUser; + _themeList = await ThemeService.GetThemesAsync(); + _tenants = await TenantService.GetTenantsAsync(); + _urls = PageState.Alias.Name; + _themes = ThemeService.GetThemeTypes(_themeList); + _containers = ThemeService.GetContainerTypes(_themeList); + _username = Constants.HostUser; } private async void TenantChanged(ChangeEventArgs e) { try { - tenantid = (string)e.Value; - if (tenantid != "-1") + _tenantid = (string)e.Value; + if (_tenantid != "-1") { - Tenant tenant = tenants.Where(item => item.TenantId == int.Parse(tenantid)).FirstOrDefault(); + Tenant tenant = _tenants.Where(item => item.TenantId == int.Parse(_tenantid)).FirstOrDefault(); if (tenant != null) { - isinitialized = tenant.IsInitialized; + _isinitialized = tenant.IsInitialized; StateHasChanged(); } } } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Tenant {TenantId} {Error}", tenantid, ex.Message); + await logger.LogError(ex, "Error Loading Tenant {TenantId} {Error}", _tenantid, ex.Message); AddModuleMessage("Error Loading Tenant", MessageType.Error); } } @@ -165,31 +165,31 @@ else { try { - themetype = (string)e.Value; - if (themetype != "") + _themetype = (string)e.Value; + if (_themetype != "") { - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); } else { - panelayouts = new Dictionary(); + _panelayouts = new Dictionary(); } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", themetype, ex.Message); + await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", _themetype, ex.Message); AddModuleMessage("Error Loading Pane Layouts For Theme", MessageType.Error); } } private async Task SaveSite() { - if (tenantid != "-1" && name != "" && urls != "" && !string.IsNullOrEmpty(themetype) && (panelayouts.Count == 0 || !string.IsNullOrEmpty(layouttype)) && !string.IsNullOrEmpty(containertype)) + if (_tenantid != "-1" && _name != "" && _urls != "" && !string.IsNullOrEmpty(_themetype) && (_panelayouts.Count == 0 || !string.IsNullOrEmpty(_layouttype)) && !string.IsNullOrEmpty(_containertype)) { bool unique = true; List aliases = await AliasService.GetAliasesAsync(); - foreach (string name in urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (string name in _urls.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (aliases.Exists(item => item.Name == name)) { @@ -200,12 +200,12 @@ else { bool isvalid = true; - if (!isinitialized) + if (!_isinitialized) { User user = new User(); user.SiteId = PageState.Site.SiteId; - user.Username = username; - user.Password = password; + user.Username = _username; + user.Password = _password; user = await UserService.LoginUserAsync(user, false, false); isvalid = user.IsAuthenticated; } @@ -215,24 +215,24 @@ else ShowProgressIndicator(); aliases = new List(); - urls = urls.Replace("\n", ","); - foreach (string name in urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + _urls = _urls.Replace("\n", ","); + foreach (string name in _urls.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { Alias alias = new Alias(); alias.Name = name; - alias.TenantId = int.Parse(tenantid); + alias.TenantId = int.Parse(_tenantid); alias.SiteId = -1; alias = await AliasService.AddAliasAsync(alias); aliases.Add(alias); } Site site = new Site(); - site.TenantId = int.Parse(tenantid); - site.Name = name; + site.TenantId = int.Parse(_tenantid); + site.Name = _name; site.LogoFileId = null; - site.DefaultThemeType = themetype; - site.DefaultLayoutType = (layouttype == null ? "" : layouttype); - site.DefaultContainerType = containertype; + site.DefaultThemeType = _themetype; + site.DefaultLayoutType = (_layouttype == null ? "" : _layouttype); + site.DefaultContainerType = _containertype; site = await SiteService.AddSiteAsync(site, aliases[0]); foreach (Alias alias in aliases) @@ -241,19 +241,19 @@ else await AliasService.UpdateAliasAsync(alias); } - if (!isinitialized) + if (!_isinitialized) { User user = new User(); user.SiteId = site.SiteId; - user.Username = username; - user.Password = password; + user.Username = _username; + user.Password = _password; user.Email = PageState.User.Email; user.DisplayName = PageState.User.DisplayName; user = await UserService.AddUserAsync(user, aliases[0]); if (user != null) { - Tenant tenant = tenants.Where(item => item.TenantId == int.Parse(tenantid)).FirstOrDefault(); + Tenant tenant = _tenants.FirstOrDefault(item => item.TenantId == int.Parse(_tenantid)); tenant.IsInitialized = true; await TenantService.UpdateTenantAsync(tenant); } @@ -265,7 +265,7 @@ else } else { - await logger.LogError("Invalid Password Entered For Host {Username}", username); + await logger.LogError("Invalid Password Entered For Host {Username}", _username); AddModuleMessage("Invalid Host Password", MessageType.Error); } } diff --git a/Oqtane.Client/UI/SiteRouter.razor b/Oqtane.Client/UI/SiteRouter.razor index c9b63239..e8e0c675 100644 --- a/Oqtane.Client/UI/SiteRouter.razor +++ b/Oqtane.Client/UI/SiteRouter.razor @@ -11,6 +11,7 @@ @inject IModuleService ModuleService @inject IModuleDefinitionService ModuleDefinitionService @inject ILogService LogService +@using System.Diagnostics.CodeAnalysis @implements IHandleAfterRender @DynamicComponent @@ -65,6 +66,7 @@ } } + [SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")] private async Task Refresh() { Alias alias = null; diff --git a/Oqtane.Client/UI/ThemeBuilder.razor b/Oqtane.Client/UI/ThemeBuilder.razor index dd12b058..2be44081 100644 --- a/Oqtane.Client/UI/ThemeBuilder.razor +++ b/Oqtane.Client/UI/ThemeBuilder.razor @@ -1,5 +1,5 @@ @namespace Oqtane.UI -@inject IJSRuntime jsRuntime +@inject IJSRuntime JsRuntime @DynamicComponent diff --git a/Oqtane.Server/Controllers/AliasController.cs b/Oqtane.Server/Controllers/AliasController.cs index 20eeba79..dc4bf37b 100644 --- a/Oqtane.Server/Controllers/AliasController.cs +++ b/Oqtane.Server/Controllers/AliasController.cs @@ -49,11 +49,11 @@ namespace Oqtane.Controllers name = WebUtility.UrlDecode(name); List aliases = _aliases.GetAliases().ToList(); Alias alias = null; - alias = aliases.Where(item => item.Name == name).FirstOrDefault(); - if (alias == null && name.Contains("/")) + alias = aliases.FirstOrDefault(item => item.Name == name); + if (name != null && (alias == null && name.Contains("/"))) { // lookup alias without folder name - alias = aliases.Find(item => item.Name == name.Substring(0, name.IndexOf("/"))); + alias = aliases.Find(item => item.Name == name.Substring(0, name.IndexOf("/", StringComparison.Ordinal))); } if (alias == null && aliases.Count > 0) { @@ -71,27 +71,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.AdminRole)] - public Alias Post([FromBody] Alias Alias) + public Alias Post([FromBody] Alias alias) { if (ModelState.IsValid) { - Alias = _aliases.AddAlias(Alias); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Alias Added {Alias}", Alias); + alias = _aliases.AddAlias(alias); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Alias Added {Alias}", alias); } - return Alias; + return alias; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.AdminRole)] - public Alias Put(int id, [FromBody] Alias Alias) + public Alias Put(int id, [FromBody] Alias alias) { if (ModelState.IsValid) { - Alias = _aliases.UpdateAlias(Alias); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Alias Updated {Alias}", Alias); + alias = _aliases.UpdateAlias(alias); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Alias Updated {Alias}", alias); } - return Alias; + return alias; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/FileController.cs b/Oqtane.Server/Controllers/FileController.cs index ea02c5ba..4cc7ac9a 100644 --- a/Oqtane.Server/Controllers/FileController.cs +++ b/Oqtane.Server/Controllers/FileController.cs @@ -61,14 +61,15 @@ namespace Oqtane.Controllers { foreach (string file in Directory.GetFiles(folder)) { - files.Add(new Models.File { Name = Path.GetFileName(file), Extension = Path.GetExtension(file).Replace(".","") }); + files.Add(new Models.File {Name = Path.GetFileName(file), Extension = Path.GetExtension(file)?.Replace(".", "")}); } } } } + return files; } - + // GET: api//siteId/folderPath [HttpGet("{siteId}/{path}")] public IEnumerable Get(int siteId, string path) @@ -95,6 +96,7 @@ namespace Oqtane.Controllers HttpContext.Response.StatusCode = 401; return null; } + return files; } @@ -103,7 +105,7 @@ namespace Oqtane.Controllers public Models.File Get(int id) { Models.File file = _files.GetFile(id); - if (_userPermissions.IsAuthorized(User,PermissionNames.View, file.Folder.Permissions)) + if (_userPermissions.IsAuthorized(User, PermissionNames.View, file.Folder.Permissions)) { return file; } @@ -118,20 +120,21 @@ namespace Oqtane.Controllers // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public Models.File Put(int id, [FromBody] Models.File File) + public Models.File Put(int id, [FromBody] Models.File file) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Folder, File.Folder.FolderId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Folder, file.Folder.FolderId, PermissionNames.Edit)) { - File = _files.UpdateFile(File); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "File Updated {File}", File); + file = _files.UpdateFile(file); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "File Updated {File}", file); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update File {File}", File); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update File {File}", file); HttpContext.Response.StatusCode = 401; - File = null; + file = null; } - return File; + + return file; } // DELETE api//5 @@ -149,6 +152,7 @@ namespace Oqtane.Controllers { System.IO.File.Delete(filepath); } + _logger.Log(LogLevel.Information, this, LogFunction.Delete, "File Deleted {File}", file); } else @@ -164,11 +168,11 @@ namespace Oqtane.Controllers { Models.File file = null; Folder folder = _folders.GetFolder(int.Parse(folderid)); - if (folder != null && _userPermissions.IsAuthorized(User,PermissionNames.Edit, folder.Permissions)) + if (folder != null && _userPermissions.IsAuthorized(User, PermissionNames.Edit, folder.Permissions)) { string folderpath = GetFolderPath(folder); CreateDirectory(folderpath); - string filename = url.Substring(url.LastIndexOf("/") + 1); + string filename = url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1); // check for allowable file extensions if (Constants.UploadableFiles.Contains(Path.GetExtension(filename).Replace(".", ""))) { @@ -180,6 +184,7 @@ namespace Oqtane.Controllers { System.IO.File.Delete(folderpath + filename); } + client.DownloadFile(url, folderpath + filename); _files.AddFile(CreateFile(filename, folder.FolderId, folderpath + filename)); } @@ -199,9 +204,10 @@ namespace Oqtane.Controllers HttpContext.Response.StatusCode = 401; file = null; } + return file; } - + // POST api//upload [HttpPost("upload")] public async Task UploadFile(string folder, IFormFile file) @@ -213,9 +219,9 @@ namespace Oqtane.Controllers if (int.TryParse(folder, out folderid)) { Folder Folder = _folders.GetFolder(folderid); - if (Folder != null && _userPermissions.IsAuthorized(User,PermissionNames.Edit, Folder.Permissions)) + if (Folder != null && _userPermissions.IsAuthorized(User, PermissionNames.Edit, Folder.Permissions)) { - folderpath = GetFolderPath(Folder); + folderpath = GetFolderPath(Folder); } } else @@ -225,6 +231,7 @@ namespace Oqtane.Controllers folderpath = GetFolderPath(folder); } } + if (folderpath != "") { CreateDirectory(folderpath); @@ -232,6 +239,7 @@ namespace Oqtane.Controllers { await file.CopyToAsync(stream); } + string upload = await MergeFile(folderpath, file.FileName); if (upload != "" && folderid != -1) { @@ -252,19 +260,19 @@ namespace Oqtane.Controllers // parse the filename which is in the format of filename.ext.part_x_y string token = ".part_"; - string parts = Path.GetExtension(filename).Replace(token, ""); // returns "x_y" - int totalparts = int.Parse(parts.Substring(parts.IndexOf("_") + 1)); - filename = filename.Substring(0, filename.IndexOf(token)); // base filename - string[] fileparts = Directory.GetFiles(folder, filename + token + "*"); // list of all file parts + string parts = Path.GetExtension(filename)?.Replace(token, ""); // returns "x_y" + int totalparts = int.Parse(parts?.Substring(parts.IndexOf("_") + 1)); + filename = filename?.Substring(0, filename.IndexOf(token)); // base filename + string[] fileParts = Directory.GetFiles(folder, filename + token + "*"); // list of all file parts // if all of the file parts exist ( note that file parts can arrive out of order ) - if (fileparts.Length == totalparts && CanAccessFiles(fileparts)) + if (fileParts.Length == totalparts && CanAccessFiles(fileParts)) { // merge file parts bool success = true; using (var stream = new FileStream(Path.Combine(folder, filename + ".tmp"), FileMode.Create)) { - foreach (string filepart in fileparts) + foreach (string filepart in fileParts) { try { @@ -283,13 +291,13 @@ namespace Oqtane.Controllers // delete file parts and rename file if (success) { - foreach (string filepart in fileparts) + foreach (string filepart in fileParts) { System.IO.File.Delete(filepart); } // check for allowable file extensions - if (!Constants.UploadableFiles.Contains(Path.GetExtension(filename).Replace(".", ""))) + if (!Constants.UploadableFiles.Contains(Path.GetExtension(filename)?.Replace(".", ""))) { System.IO.File.Delete(Path.Combine(folder, filename + ".tmp")); } @@ -300,17 +308,19 @@ namespace Oqtane.Controllers { System.IO.File.Delete(Path.Combine(folder, filename)); } + // rename file now that the entire process is completed System.IO.File.Move(Path.Combine(folder, filename + ".tmp"), Path.Combine(folder, filename)); _logger.Log(LogLevel.Information, this, LogFunction.Create, "File Uploaded {File}", Path.Combine(folder, filename)); } + merged = filename; } } // clean up file parts which are more than 2 hours old ( which can happen if a prior file upload failed ) - fileparts = Directory.GetFiles(folder, "*" + token + "*"); - foreach (string filepart in fileparts) + fileParts = Directory.GetFiles(folder, "*" + token + "*"); + foreach (string filepart in fileParts) { DateTime createddate = System.IO.File.GetCreationTime(filepart).ToUniversalTime(); if (createddate < DateTime.UtcNow.AddHours(-2)) @@ -339,7 +349,7 @@ namespace Oqtane.Controllers locked = false; } catch // file is locked by another process - { + { Thread.Sleep(1000); // wait 1 second } finally @@ -349,13 +359,16 @@ namespace Oqtane.Controllers stream.Close(); } } + attempts += 1; } + if (locked && canaccess) { canaccess = false; } } + return canaccess; } @@ -364,7 +377,7 @@ namespace Oqtane.Controllers public IActionResult Download(int id) { Models.File file = _files.GetFile(id); - if (file != null && _userPermissions.IsAuthorized(User,PermissionNames.View, file.Folder.Permissions)) + if (file != null && _userPermissions.IsAuthorized(User, PermissionNames.View, file.Folder.Permissions)) { string filepath = GetFolderPath(file.Folder) + file.Name; if (System.IO.File.Exists(filepath)) @@ -402,7 +415,7 @@ namespace Oqtane.Controllers if (!Directory.Exists(folderpath)) { string path = ""; - string[] folders = folderpath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); + string[] folders = folderpath.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries); foreach (string folder in folders) { path += folder + "\\"; @@ -422,7 +435,7 @@ namespace Oqtane.Controllers FileInfo fileinfo = new FileInfo(filepath); file.Extension = fileinfo.Extension.ToLower().Replace(".", ""); - file.Size = (int)fileinfo.Length; + file.Size = (int) fileinfo.Length; file.ImageHeight = 0; file.ImageWidth = 0; @@ -434,6 +447,7 @@ namespace Oqtane.Controllers file.ImageHeight = image.Height; file.ImageWidth = image.Width; } + stream.Close(); } From 5b3feaf26fbd0bf9ccbf6e49b9efa7ea5e9f3627 Mon Sep 17 00:00:00 2001 From: Pavel Vesely Date: Sun, 15 Mar 2020 09:38:37 +0100 Subject: [PATCH 2/3] Server naming fixes and cleanup Server is now completely cleaned up and without warnings --- Oqtane.Server/Controllers/AliasController.cs | 4 +- Oqtane.Server/Controllers/FileController.cs | 51 ++--- Oqtane.Server/Controllers/FolderController.cs | 46 ++--- .../Controllers/InstallationController.cs | 27 +-- Oqtane.Server/Controllers/JobController.cs | 20 +- Oqtane.Server/Controllers/JobLogController.cs | 20 +- Oqtane.Server/Controllers/LogController.cs | 8 +- Oqtane.Server/Controllers/ModuleController.cs | 47 +++-- .../Controllers/ModuleDefinitionController.cs | 11 +- .../Controllers/NotificationController.cs | 37 ++-- .../Controllers/PackageController.cs | 1 + Oqtane.Server/Controllers/PageController.cs | 38 ++-- .../Controllers/PageModuleController.cs | 40 ++-- .../Controllers/ProfileController.cs | 20 +- Oqtane.Server/Controllers/RoleController.cs | 20 +- .../Controllers/SettingController.cs | 49 +++-- Oqtane.Server/Controllers/SiteController.cs | 30 ++- Oqtane.Server/Controllers/TenantController.cs | 20 +- Oqtane.Server/Controllers/ThemeController.cs | 6 +- Oqtane.Server/Controllers/UserController.cs | 187 +++++++++--------- .../Controllers/UserRoleController.cs | 24 +-- .../Extensions/AssemblyExtensions.cs | 4 +- .../Extensions/OqtaneMvcBuilderExtensions.cs | 3 +- .../OqtaneServiceCollectionExtensions.cs | 23 ++- .../Infrastructure/InstallationManager.cs | 60 +++--- .../Interfaces/IInstallationManager.cs | 4 +- .../Infrastructure/Interfaces/ILogManager.cs | 16 +- .../Infrastructure/Interfaces/ISyncManager.cs | 11 +- .../Infrastructure/Jobs/HostedServiceBase.cs | 88 ++++----- .../Infrastructure/Jobs/NotificationJob.cs | 34 ++-- Oqtane.Server/Infrastructure/LogManager.cs | 81 ++++---- Oqtane.Server/Infrastructure/SyncManager.cs | 19 +- .../Controllers/HtmlTextController.cs | 28 +-- .../HtmlText/Manager/HtmlTextManager.cs | 16 +- .../HtmlText/Repository/HtmlTextContext.cs | 2 +- .../HtmlText/Repository/HtmlTextRepository.cs | 56 ++---- .../Repository/IHtmlTextRepository.cs | 11 +- Oqtane.Server/Modules/IPortable.cs | 4 +- Oqtane.Server/Pages/_Host.cshtml | 1 - Oqtane.Server/Program.cs | 8 +- Oqtane.Server/Repository/AliasRepository.cs | 26 +-- .../Repository/Context/DBContextBase.cs | 12 +- .../Repository/Context/MasterDBContext.cs | 10 +- .../Repository/Context/TenantDBContext.cs | 2 +- Oqtane.Server/Repository/FileRepository.cs | 34 ++-- Oqtane.Server/Repository/FolderRepository.cs | 42 ++-- .../Repository/Interfaces/IAliasRepository.cs | 8 +- .../Repository/Interfaces/IFileRepository.cs | 10 +- .../Interfaces/IFolderRepository.cs | 12 +- .../Interfaces/IJobLogRepository.cs | 8 +- .../Repository/Interfaces/IJobRepository.cs | 8 +- .../Repository/Interfaces/ILogRepository.cs | 10 +- .../Interfaces/IModuleDefinitionRepository.cs | 8 +- .../Interfaces/IModuleRepository.cs | 14 +- .../Interfaces/INotificationRepository.cs | 10 +- .../Interfaces/IPageModuleRepository.cs | 14 +- .../Repository/Interfaces/IPageRepository.cs | 14 +- .../Interfaces/IPermissionRepository.cs | 22 +-- .../Interfaces/IProfileRepository.cs | 10 +- .../Repository/Interfaces/IRoleRepository.cs | 12 +- .../Interfaces/ISettingRepository.cs | 10 +- .../Repository/Interfaces/ISiteRepository.cs | 8 +- .../Interfaces/ITenantRepository.cs | 12 +- .../Repository/Interfaces/IUserRepository.cs | 10 +- .../Interfaces/IUserRoleRepository.cs | 12 +- Oqtane.Server/Repository/JobLogRepository.cs | 24 +-- Oqtane.Server/Repository/JobRepository.cs | 28 +-- Oqtane.Server/Repository/LogRepository.cs | 47 ++--- .../Repository/ModuleDefinitionRepository.cs | 99 +++++----- Oqtane.Server/Repository/ModuleRepository.cs | 53 ++--- .../Repository/NotificationRepository.cs | 50 +++-- .../Repository/PageModuleRepository.cs | 42 ++-- Oqtane.Server/Repository/PageRepository.cs | 50 ++--- .../Repository/PermissionRepository.cs | 89 +++++---- Oqtane.Server/Repository/ProfileRepository.cs | 30 +-- Oqtane.Server/Repository/RoleRepository.cs | 34 ++-- Oqtane.Server/Repository/SettingRepository.cs | 32 +-- Oqtane.Server/Repository/SiteRepository.cs | 27 +-- Oqtane.Server/Repository/TenantRepository.cs | 25 ++- Oqtane.Server/Repository/TenantResolver.cs | 52 ++--- Oqtane.Server/Repository/ThemeRepository.cs | 39 ++-- Oqtane.Server/Repository/UserRepository.cs | 8 +- .../Repository/UserRoleRepository.cs | 36 ++-- .../Security/ClaimsPrincipalFactory.cs | 2 +- Oqtane.Server/Security/IUserPermissions.cs | 6 +- Oqtane.Server/Security/PermissionHandler.cs | 8 +- Oqtane.Server/Security/UserPermissions.cs | 47 +++-- Oqtane.Server/Startup.cs | 67 +++---- Oqtane.Shared/Models/Log.cs | 1 - Oqtane.Shared/Models/Module.cs | 4 +- Oqtane.Shared/Security/UserSecurity.cs | 62 +++--- Oqtane.Upgrade/Program.cs | 21 +- 92 files changed, 1223 insertions(+), 1273 deletions(-) diff --git a/Oqtane.Server/Controllers/AliasController.cs b/Oqtane.Server/Controllers/AliasController.cs index dc4bf37b..94633fd4 100644 --- a/Oqtane.Server/Controllers/AliasController.cs +++ b/Oqtane.Server/Controllers/AliasController.cs @@ -1,14 +1,14 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; using System.Linq; using System; using System.Net; using System.Globalization; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { diff --git a/Oqtane.Server/Controllers/FileController.cs b/Oqtane.Server/Controllers/FileController.cs index 4cc7ac9a..35026847 100644 --- a/Oqtane.Server/Controllers/FileController.cs +++ b/Oqtane.Server/Controllers/FileController.cs @@ -2,8 +2,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Oqtane.Infrastructure; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System; @@ -15,6 +13,10 @@ using Oqtane.Security; using System.Linq; using System.Drawing; using System.Net; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; + +// ReSharper disable StringIndexOfIsCultureSpecific.1 namespace Oqtane.Controllers { @@ -170,23 +172,23 @@ namespace Oqtane.Controllers Folder folder = _folders.GetFolder(int.Parse(folderid)); if (folder != null && _userPermissions.IsAuthorized(User, PermissionNames.Edit, folder.Permissions)) { - string folderpath = GetFolderPath(folder); - CreateDirectory(folderpath); + string folderPath = GetFolderPath(folder); + CreateDirectory(folderPath); string filename = url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1); // check for allowable file extensions if (Constants.UploadableFiles.Contains(Path.GetExtension(filename).Replace(".", ""))) { try { - var client = new System.Net.WebClient(); + var client = new WebClient(); // remove file if it already exists - if (System.IO.File.Exists(folderpath + filename)) + if (System.IO.File.Exists(folderPath + filename)) { - System.IO.File.Delete(folderpath + filename); + System.IO.File.Delete(folderPath + filename); } - client.DownloadFile(url, folderpath + filename); - _files.AddFile(CreateFile(filename, folder.FolderId, folderpath + filename)); + client.DownloadFile(url, folderPath + filename); + _files.AddFile(CreateFile(filename, folder.FolderId, folderPath + filename)); } catch { @@ -202,7 +204,6 @@ namespace Oqtane.Controllers { _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Download File {Url} {FolderId}", url, folderid); HttpContext.Response.StatusCode = 401; - file = null; } return file; @@ -214,36 +215,36 @@ namespace Oqtane.Controllers { if (file.Length > 0) { - string folderpath = ""; - int folderid = -1; - if (int.TryParse(folder, out folderid)) + string folderPath = ""; + + if (int.TryParse(folder, out int folderId)) { - Folder Folder = _folders.GetFolder(folderid); - if (Folder != null && _userPermissions.IsAuthorized(User, PermissionNames.Edit, Folder.Permissions)) + Folder virtualFolder = _folders.GetFolder(folderId); + if (virtualFolder != null && _userPermissions.IsAuthorized(User, PermissionNames.Edit, virtualFolder.Permissions)) { - folderpath = GetFolderPath(Folder); + folderPath = GetFolderPath(virtualFolder); } } else { if (User.IsInRole(Constants.HostRole)) { - folderpath = GetFolderPath(folder); + folderPath = GetFolderPath(folder); } } - if (folderpath != "") + if (folderPath != "") { - CreateDirectory(folderpath); - using (var stream = new FileStream(Path.Combine(folderpath, file.FileName), FileMode.Create)) + CreateDirectory(folderPath); + using (var stream = new FileStream(Path.Combine(folderPath, file.FileName), FileMode.Create)) { await file.CopyToAsync(stream); } - string upload = await MergeFile(folderpath, file.FileName); - if (upload != "" && folderid != -1) + string upload = await MergeFile(folderPath, file.FileName); + if (upload != "" && folderId != -1) { - _files.AddFile(CreateFile(upload, folderid, folderpath + upload)); + _files.AddFile(CreateFile(upload, folderId, folderPath + upload)); } } else @@ -341,7 +342,7 @@ namespace Oqtane.Controllers { int attempts = 0; bool locked = true; - while (attempts < 5 && locked == true) + while (attempts < 5 && locked) { try { @@ -415,7 +416,7 @@ namespace Oqtane.Controllers if (!Directory.Exists(folderpath)) { string path = ""; - string[] folders = folderpath.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries); + string[] folders = folderpath.Split(new[] {'\\'}, StringSplitOptions.RemoveEmptyEntries); foreach (string folder in folders) { path += folder + "\\"; diff --git a/Oqtane.Server/Controllers/FolderController.cs b/Oqtane.Server/Controllers/FolderController.cs index 24da6e17..0a7c5c13 100644 --- a/Oqtane.Server/Controllers/FolderController.cs +++ b/Oqtane.Server/Controllers/FolderController.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Linq; using System.Net; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; namespace Oqtane.Controllers @@ -86,14 +86,14 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.RegisteredRole)] - public Folder Post([FromBody] Folder Folder) + public Folder Post([FromBody] Folder folder) { if (ModelState.IsValid) { string permissions; - if (Folder.ParentId != null) + if (folder.ParentId != null) { - permissions = _folders.GetFolder(Folder.ParentId.Value).Permissions; + permissions = _folders.GetFolder(folder.ParentId.Value).Permissions; } else { @@ -101,46 +101,46 @@ namespace Oqtane.Controllers } if (_userPermissions.IsAuthorized(User,PermissionNames.Edit, permissions)) { - if (string.IsNullOrEmpty(Folder.Path) && Folder.ParentId != null) + if (string.IsNullOrEmpty(folder.Path) && folder.ParentId != null) { - Folder parent = _folders.GetFolder(Folder.ParentId.Value); - Folder.Path = parent.Path + Folder.Name + "\\"; + Folder parent = _folders.GetFolder(folder.ParentId.Value); + folder.Path = parent.Path + folder.Name + "\\"; } - Folder = _folders.AddFolder(Folder); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Folder Added {Folder}", Folder); + folder = _folders.AddFolder(folder); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Folder Added {Folder}", folder); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Folder {Folder}", Folder); + _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Folder {Folder}", folder); HttpContext.Response.StatusCode = 401; - Folder = null; + folder = null; } } - return Folder; + return folder; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public Folder Put(int id, [FromBody] Folder Folder) + public Folder Put(int id, [FromBody] Folder folder) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Folder, Folder.FolderId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Folder, folder.FolderId, PermissionNames.Edit)) { - if (string.IsNullOrEmpty(Folder.Path) && Folder.ParentId != null) + if (string.IsNullOrEmpty(folder.Path) && folder.ParentId != null) { - Folder parent = _folders.GetFolder(Folder.ParentId.Value); - Folder.Path = parent.Path + Folder.Name + "\\"; + Folder parent = _folders.GetFolder(folder.ParentId.Value); + folder.Path = parent.Path + folder.Name + "\\"; } - Folder = _folders.UpdateFolder(Folder); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Folder Updated {Folder}", Folder); + folder = _folders.UpdateFolder(folder); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Folder Updated {Folder}", folder); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Folder {Folder}", Folder); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Folder {Folder}", folder); HttpContext.Response.StatusCode = 401; - Folder = null; + folder = null; } - return Folder; + return folder; } // PUT api//?siteid=x&folderid=y&parentid=z diff --git a/Oqtane.Server/Controllers/InstallationController.cs b/Oqtane.Server/Controllers/InstallationController.cs index 7f8b358f..cde7a4be 100644 --- a/Oqtane.Server/Controllers/InstallationController.cs +++ b/Oqtane.Server/Controllers/InstallationController.cs @@ -1,10 +1,8 @@ using DbUp; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using Oqtane.Infrastructure; using Oqtane.Models; using Oqtane.Shared; using System; @@ -13,6 +11,9 @@ using System.IO; using System.Linq; using System.Reflection; using System.Threading; +using Oqtane.Infrastructure.Interfaces; + +// ReSharper disable StringIndexOfIsCultureSpecific.1 namespace Oqtane.Controllers { @@ -30,7 +31,7 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] - public GenericResponse Post([FromBody] string connectionstring) + public GenericResponse Post([FromBody] string connectionString) { var response = new GenericResponse { Success = false, Message = "" }; @@ -38,7 +39,7 @@ namespace Oqtane.Controllers { bool master = false; string defaultconnectionstring = _config.GetConnectionString("DefaultConnection"); - if (string.IsNullOrEmpty(defaultconnectionstring) || connectionstring == defaultconnectionstring) + if (string.IsNullOrEmpty(defaultconnectionstring) || connectionString == defaultconnectionstring) { master = true; } @@ -52,9 +53,9 @@ namespace Oqtane.Controllers if (!exists) { string datadirectory = AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); - connectionstring = connectionstring.Replace("|DataDirectory|", datadirectory); + connectionString = connectionString.Replace("|DataDirectory|", datadirectory); - SqlConnection connection = new SqlConnection(connectionstring); + SqlConnection connection = new SqlConnection(connectionString); try { using (connection) @@ -73,7 +74,7 @@ namespace Oqtane.Controllers { string masterConnectionString = ""; string databaseName = ""; - string[] fragments = connectionstring.Split(';', StringSplitOptions.RemoveEmptyEntries); + string[] fragments = connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (string fragment in fragments) { if (fragment.ToLower().Contains("initial catalog=") || fragment.ToLower().Contains("database=")) @@ -95,7 +96,7 @@ namespace Oqtane.Controllers { connection.Open(); SqlCommand command; - if (connectionstring.ToLower().Contains("attachdbfilename=")) // LocalDB + if (connectionString.ToLower().Contains("attachdbfilename=")) // LocalDB { command = new SqlCommand("CREATE DATABASE [" + databaseName + "] ON ( NAME = '" + databaseName + "', FILENAME = '" + datadirectory + "\\" + databaseName + ".mdf')", connection); } @@ -126,11 +127,11 @@ namespace Oqtane.Controllers { initializationScript = reader.ReadToEnd(); } - initializationScript = initializationScript.Replace("{ConnectionString}", connectionstring.Replace(datadirectory, "|DataDirectory|")); + initializationScript = initializationScript.Replace("{ConnectionString}", connectionString.Replace(datadirectory, "|DataDirectory|")); initializationScript = initializationScript.Replace("{Alias}", HttpContext.Request.Host.Value); } - var dbUpgradeConfig = DeployChanges.To.SqlDatabase(connectionstring) + var dbUpgradeConfig = DeployChanges.To.SqlDatabase(connectionString) .WithScript(new DbUp.Engine.SqlScript("Master.sql", initializationScript)) .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly()); // tenant scripts should be added to /Scripts folder as Embedded Resources var dbUpgrade = dbUpgradeConfig.Build(); @@ -151,9 +152,9 @@ namespace Oqtane.Controllers { config = reader.ReadToEnd(); } - connectionstring = connectionstring.Replace(datadirectory, "|DataDirectory|"); - connectionstring = connectionstring.Replace(@"\", @"\\"); - config = config.Replace("DefaultConnection\": \"", "DefaultConnection\": \"" + connectionstring); + connectionString = connectionString.Replace(datadirectory, "|DataDirectory|"); + connectionString = connectionString.Replace(@"\", @"\\"); + config = config.Replace("DefaultConnection\": \"", "DefaultConnection\": \"" + connectionString); using (StreamWriter writer = new StreamWriter(Directory.GetCurrentDirectory() + "\\appsettings.json")) { writer.WriteLine(config); diff --git a/Oqtane.Server/Controllers/JobController.cs b/Oqtane.Server/Controllers/JobController.cs index 0f5bdea3..997bad67 100644 --- a/Oqtane.Server/Controllers/JobController.cs +++ b/Oqtane.Server/Controllers/JobController.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; using System; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -44,27 +44,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.HostRole)] - public Job Post([FromBody] Job Job) + public Job Post([FromBody] Job job) { if (ModelState.IsValid) { - Job = _jobs.AddJob(Job); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Job Added {Job}", Job); + job = _jobs.AddJob(job); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Job Added {Job}", job); } - return Job; + return job; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.HostRole)] - public Job Put(int id, [FromBody] Job Job) + public Job Put(int id, [FromBody] Job job) { if (ModelState.IsValid) { - Job = _jobs.UpdateJob(Job); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Job Updated {Job}", Job); + job = _jobs.UpdateJob(job); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Job Updated {Job}", job); } - return Job; + return job; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/JobLogController.cs b/Oqtane.Server/Controllers/JobLogController.cs index 2d9d4b7e..769e5e27 100644 --- a/Oqtane.Server/Controllers/JobLogController.cs +++ b/Oqtane.Server/Controllers/JobLogController.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -39,27 +39,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.HostRole)] - public JobLog Post([FromBody] JobLog JobLog) + public JobLog Post([FromBody] JobLog jobLog) { if (ModelState.IsValid) { - JobLog = _jobLogs.AddJobLog(JobLog); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Job Log Added {JobLog}", JobLog); + jobLog = _jobLogs.AddJobLog(jobLog); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Job Log Added {JobLog}", jobLog); } - return JobLog; + return jobLog; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.HostRole)] - public JobLog Put(int id, [FromBody] JobLog JobLog) + public JobLog Put(int id, [FromBody] JobLog jobLog) { if (ModelState.IsValid) { - JobLog = _jobLogs.UpdateJobLog(JobLog); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Job Log Updated {JobLog}", JobLog); + jobLog = _jobLogs.UpdateJobLog(jobLog); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Job Log Updated {JobLog}", jobLog); } - return JobLog; + return jobLog; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/LogController.cs b/Oqtane.Server/Controllers/LogController.cs index 9942cf8b..d59b9411 100644 --- a/Oqtane.Server/Controllers/LogController.cs +++ b/Oqtane.Server/Controllers/LogController.cs @@ -1,9 +1,9 @@ using Microsoft.AspNetCore.Mvc; using Oqtane.Models; using System.Collections.Generic; -using Oqtane.Repository; -using Oqtane.Infrastructure; using Microsoft.AspNetCore.Authorization; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Shared; namespace Oqtane.Controllers @@ -39,11 +39,11 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] - public void Post([FromBody] Log Log) + public void Post([FromBody] Log log) { if (ModelState.IsValid) { - _logger.Log(Log); + _logger.Log(log); } } } diff --git a/Oqtane.Server/Controllers/ModuleController.cs b/Oqtane.Server/Controllers/ModuleController.cs index 40df2585..6443e9a8 100644 --- a/Oqtane.Server/Controllers/ModuleController.cs +++ b/Oqtane.Server/Controllers/ModuleController.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Linq; -using System.Reflection; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; namespace Oqtane.Controllers @@ -31,15 +30,15 @@ namespace Oqtane.Controllers // GET: api/?siteid=x [HttpGet] - public IEnumerable Get(string siteid) + public IEnumerable Get(string siteid) { List moduledefinitions = _moduleDefinitions.GetModuleDefinitions(int.Parse(siteid)).ToList(); - List modules = new List(); + List modules = new List(); foreach (PageModule pagemodule in _pageModules.GetPageModules(int.Parse(siteid))) { if (_userPermissions.IsAuthorized(User,PermissionNames.View, pagemodule.Module.Permissions)) { - Models.Module module = new Models.Module(); + Module module = new Module(); module.SiteId = pagemodule.Module.SiteId; module.ModuleDefinitionName = pagemodule.Module.ModuleDefinitionName; module.Permissions = pagemodule.Module.Permissions; @@ -67,9 +66,9 @@ namespace Oqtane.Controllers // GET api//5 [HttpGet("{id}")] - public Models.Module Get(int id) + public Module Get(int id) { - Models.Module module = _modules.GetModule(id); + Module module = _modules.GetModule(id); if (_userPermissions.IsAuthorized(User,PermissionNames.View, module.Permissions)) { List moduledefinitions = _moduleDefinitions.GetModuleDefinitions(module.SiteId).ToList(); @@ -87,39 +86,39 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.RegisteredRole)] - public Models.Module Post([FromBody] Models.Module Module) + public Module Post([FromBody] Module module) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, Module.PageId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, module.PageId, PermissionNames.Edit)) { - Module = _modules.AddModule(Module); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Module Added {Module}", Module); + module = _modules.AddModule(module); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Module Added {Module}", module); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Module {Module}", Module); + _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Module {Module}", module); HttpContext.Response.StatusCode = 401; - Module = null; + module = null; } - return Module; + return module; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public Models.Module Put(int id, [FromBody] Models.Module Module) + public Module Put(int id, [FromBody] Module module) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Module, Module.ModuleId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Module, module.ModuleId, PermissionNames.Edit)) { - Module = _modules.UpdateModule(Module); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Module Updated {Module}", Module); + module = _modules.UpdateModule(module); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Module Updated {Module}", module); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Module {Module}", Module); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Module {Module}", module); HttpContext.Response.StatusCode = 401; - Module = null; + module = null; } - return Module; + return module; } // DELETE api//5 @@ -160,12 +159,12 @@ namespace Oqtane.Controllers // POST api//import?moduleid=x [HttpPost("import")] [Authorize(Roles = Constants.RegisteredRole)] - public bool Import(int moduleid, [FromBody] string Content) + public bool Import(int moduleid, [FromBody] string content) { bool success = false; if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Module, moduleid, PermissionNames.Edit)) { - success = _modules.ImportModule(moduleid, Content); + success = _modules.ImportModule(moduleid, content); } else { diff --git a/Oqtane.Server/Controllers/ModuleDefinitionController.cs b/Oqtane.Server/Controllers/ModuleDefinitionController.cs index 10bd92e7..77a50d8c 100644 --- a/Oqtane.Server/Controllers/ModuleDefinitionController.cs +++ b/Oqtane.Server/Controllers/ModuleDefinitionController.cs @@ -1,15 +1,16 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using Microsoft.AspNetCore.Authorization; -using Oqtane.Infrastructure; using System.IO; using System.Reflection; using System.Linq; using Microsoft.AspNetCore.Hosting; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; +// ReSharper disable StringIndexOfIsCultureSpecific.1 namespace Oqtane.Controllers { @@ -66,12 +67,12 @@ namespace Oqtane.Controllers // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.AdminRole)] - public void Put(int id, [FromBody] ModuleDefinition ModuleDefinition) + public void Put(int id, [FromBody] ModuleDefinition moduleDefinition) { if (ModelState.IsValid) { - _moduleDefinitions.UpdateModuleDefinition(ModuleDefinition); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Module Definition Updated {ModuleDefinition}", ModuleDefinition); + _moduleDefinitions.UpdateModuleDefinition(moduleDefinition); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Module Definition Updated {ModuleDefinition}", moduleDefinition); } } diff --git a/Oqtane.Server/Controllers/NotificationController.cs b/Oqtane.Server/Controllers/NotificationController.cs index cecc9216..cb4a1afa 100644 --- a/Oqtane.Server/Controllers/NotificationController.cs +++ b/Oqtane.Server/Controllers/NotificationController.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; -using Microsoft.AspNetCore.Http; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; namespace Oqtane.Controllers @@ -49,38 +48,38 @@ namespace Oqtane.Controllers [Authorize(Roles = Constants.RegisteredRole)] public Notification Get(int id) { - Notification Notification = _notifications.GetNotification(id); - if (!(IsAuthorized(Notification.FromUserId) || IsAuthorized(Notification.ToUserId))) + Notification notification = _notifications.GetNotification(id); + if (!(IsAuthorized(notification.FromUserId) || IsAuthorized(notification.ToUserId))) { - Notification = null; + notification = null; } - return Notification; + return notification; } // POST api/ [HttpPost] [Authorize(Roles = Constants.RegisteredRole)] - public Notification Post([FromBody] Notification Notification) + public Notification Post([FromBody] Notification notification) { - if (IsAuthorized(Notification.FromUserId)) + if (IsAuthorized(notification.FromUserId)) { - Notification = _notifications.AddNotification(Notification); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Notification Added {Notification}", Notification); + notification = _notifications.AddNotification(notification); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Notification Added {Notification}", notification); } - return Notification; + return notification; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public Notification Put(int id, [FromBody] Notification Notification) + public Notification Put(int id, [FromBody] Notification notification) { - if (IsAuthorized(Notification.FromUserId)) + if (IsAuthorized(notification.FromUserId)) { - Notification = _notifications.UpdateNotification(Notification); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Notification Updated {Folder}", Notification); + notification = _notifications.UpdateNotification(notification); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Notification Updated {Folder}", notification); } - return Notification; + return notification; } // DELETE api//5 @@ -88,8 +87,8 @@ namespace Oqtane.Controllers [Authorize(Roles = Constants.RegisteredRole)] public void Delete(int id) { - Notification Notification = _notifications.GetNotification(id); - if (IsAuthorized(Notification.FromUserId) || IsAuthorized(Notification.ToUserId)) + Notification notification = _notifications.GetNotification(id); + if (IsAuthorized(notification.FromUserId) || IsAuthorized(notification.ToUserId)) { _notifications.DeleteNotification(id); _logger.Log(LogLevel.Information, this, LogFunction.Delete, "Notification Deleted {NotificationId}", id); diff --git a/Oqtane.Server/Controllers/PackageController.cs b/Oqtane.Server/Controllers/PackageController.cs index 5b69d426..a6ea13ef 100644 --- a/Oqtane.Server/Controllers/PackageController.cs +++ b/Oqtane.Server/Controllers/PackageController.cs @@ -11,6 +11,7 @@ using System.Linq; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Authorization; using Oqtane.Shared; +// ReSharper disable PartialTypeWithSinglePart namespace Oqtane.Controllers { diff --git a/Oqtane.Server/Controllers/PageController.cs b/Oqtane.Server/Controllers/PageController.cs index f7167a38..394146dc 100644 --- a/Oqtane.Server/Controllers/PageController.cs +++ b/Oqtane.Server/Controllers/PageController.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Linq; -using Oqtane.Infrastructure; using Oqtane.Security; using System.Net; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -99,14 +99,14 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.RegisteredRole)] - public Page Post([FromBody] Page Page) + public Page Post([FromBody] Page page) { if (ModelState.IsValid) { string permissions; - if (Page.ParentId != null) + if (page.ParentId != null) { - permissions = _pages.GetPage(Page.ParentId.Value).Permissions; + permissions = _pages.GetPage(page.ParentId.Value).Permissions; } else { @@ -115,18 +115,18 @@ namespace Oqtane.Controllers if (_userPermissions.IsAuthorized(User,PermissionNames.Edit, permissions)) { - Page = _pages.AddPage(Page); - _syncManager.AddSyncEvent(EntityNames.Site, Page.SiteId); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Page Added {Page}", Page); + page = _pages.AddPage(page); + _syncManager.AddSyncEvent(EntityNames.Site, page.SiteId); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Page Added {Page}", page); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Page {Page}", Page); + _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Page {Page}", page); HttpContext.Response.StatusCode = 401; - Page = null; + page = null; } } - return Page; + return page; } // POST api//5?userid=x @@ -195,21 +195,21 @@ namespace Oqtane.Controllers // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public Page Put(int id, [FromBody] Page Page) + public Page Put(int id, [FromBody] Page page) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, Page.PageId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, page.PageId, PermissionNames.Edit)) { - Page = _pages.UpdatePage(Page); - _syncManager.AddSyncEvent(EntityNames.Site, Page.SiteId); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Page Updated {Page}", Page); + page = _pages.UpdatePage(page); + _syncManager.AddSyncEvent(EntityNames.Site, page.SiteId); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Page Updated {Page}", page); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Page {Page}", Page); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Page {Page}", page); HttpContext.Response.StatusCode = 401; - Page = null; + page = null; } - return Page; + return page; } // PUT api//?siteid=x&pageid=y&parentid=z diff --git a/Oqtane.Server/Controllers/PageModuleController.cs b/Oqtane.Server/Controllers/PageModuleController.cs index 265a3f00..6c30a364 100644 --- a/Oqtane.Server/Controllers/PageModuleController.cs +++ b/Oqtane.Server/Controllers/PageModuleController.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Linq; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; namespace Oqtane.Controllers @@ -14,15 +14,13 @@ namespace Oqtane.Controllers public class PageModuleController : Controller { private readonly IPageModuleRepository _pageModules; - private readonly IModuleRepository _modules; private readonly IUserPermissions _userPermissions; private readonly ISyncManager _syncManager; private readonly ILogManager _logger; - public PageModuleController(IPageModuleRepository pageModules, IModuleRepository modules, IUserPermissions userPermissions, ISyncManager syncManager, ILogManager logger) + public PageModuleController(IPageModuleRepository pageModules, IUserPermissions userPermissions, ISyncManager syncManager, ILogManager logger) { _pageModules = pageModules; - _modules = modules; _userPermissions = userPermissions; _syncManager = syncManager; _logger = logger; @@ -65,41 +63,41 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.RegisteredRole)] - public PageModule Post([FromBody] PageModule PageModule) + public PageModule Post([FromBody] PageModule pageModule) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, PageModule.PageId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, pageModule.PageId, PermissionNames.Edit)) { - PageModule = _pageModules.AddPageModule(PageModule); - _syncManager.AddSyncEvent(EntityNames.Page, PageModule.PageId); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Page Module Added {PageModule}", PageModule); + pageModule = _pageModules.AddPageModule(pageModule); + _syncManager.AddSyncEvent(EntityNames.Page, pageModule.PageId); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Page Module Added {PageModule}", pageModule); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add PageModule {PageModule}", PageModule); + _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add PageModule {PageModule}", pageModule); HttpContext.Response.StatusCode = 401; - PageModule = null; + pageModule = null; } - return PageModule; + return pageModule; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.RegisteredRole)] - public PageModule Put(int id, [FromBody] PageModule PageModule) + public PageModule Put(int id, [FromBody] PageModule pageModule) { - if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Module, PageModule.ModuleId, PermissionNames.Edit)) + if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Module, pageModule.ModuleId, PermissionNames.Edit)) { - PageModule = _pageModules.UpdatePageModule(PageModule); - _syncManager.AddSyncEvent(EntityNames.Page, PageModule.PageId); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Page Module Updated {PageModule}", PageModule); + pageModule = _pageModules.UpdatePageModule(pageModule); + _syncManager.AddSyncEvent(EntityNames.Page, pageModule.PageId); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Page Module Updated {PageModule}", pageModule); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update PageModule {PageModule}", PageModule); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update PageModule {PageModule}", pageModule); HttpContext.Response.StatusCode = 401; - PageModule = null; + pageModule = null; } - return PageModule; + return pageModule; } // PUT api//?pageid=x&pane=y diff --git a/Oqtane.Server/Controllers/ProfileController.cs b/Oqtane.Server/Controllers/ProfileController.cs index b325fccf..0244515b 100644 --- a/Oqtane.Server/Controllers/ProfileController.cs +++ b/Oqtane.Server/Controllers/ProfileController.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -37,27 +37,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.AdminRole)] - public Profile Post([FromBody] Profile Profile) + public Profile Post([FromBody] Profile profile) { if (ModelState.IsValid) { - Profile = _profiles.AddProfile(Profile); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Profile Added {Profile}", Profile); + profile = _profiles.AddProfile(profile); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Profile Added {Profile}", profile); } - return Profile; + return profile; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.AdminRole)] - public Profile Put(int id, [FromBody] Profile Profile) + public Profile Put(int id, [FromBody] Profile profile) { if (ModelState.IsValid) { - Profile = _profiles.UpdateProfile(Profile); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Profile Updated {Profile}", Profile); + profile = _profiles.UpdateProfile(profile); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Profile Updated {Profile}", profile); } - return Profile; + return profile; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/RoleController.cs b/Oqtane.Server/Controllers/RoleController.cs index 7de3ae22..d6767d57 100644 --- a/Oqtane.Server/Controllers/RoleController.cs +++ b/Oqtane.Server/Controllers/RoleController.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -39,27 +39,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.AdminRole)] - public Role Post([FromBody] Role Role) + public Role Post([FromBody] Role role) { if (ModelState.IsValid) { - Role = _roles.AddRole(Role); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Role Added {Role}", Role); + role = _roles.AddRole(role); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Role Added {Role}", role); } - return Role; + return role; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.AdminRole)] - public Role Put(int id, [FromBody] Role Role) + public Role Put(int id, [FromBody] Role role) { if (ModelState.IsValid) { - Role = _roles.UpdateRole(Role); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Role Updated {Role}", Role); + role = _roles.UpdateRole(role); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Role Updated {Role}", role); } - return Role; + return role; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/SettingController.cs b/Oqtane.Server/Controllers/SettingController.cs index c0a8571d..326aa276 100644 --- a/Oqtane.Server/Controllers/SettingController.cs +++ b/Oqtane.Server/Controllers/SettingController.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using Oqtane.Security; -using Oqtane.Infrastructure; using System.Linq; -using Microsoft.AspNetCore.Http; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -62,38 +61,38 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] - public Setting Post([FromBody] Setting Setting) + public Setting Post([FromBody] Setting setting) { - if (ModelState.IsValid && IsAuthorized(Setting.EntityName, Setting.EntityId, PermissionNames.Edit)) + if (ModelState.IsValid && IsAuthorized(setting.EntityName, setting.EntityId, PermissionNames.Edit)) { - Setting = _settings.AddSetting(Setting); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Setting Added {Setting}", Setting); + setting = _settings.AddSetting(setting); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Setting Added {Setting}", setting); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Setting {Setting}", Setting); + _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Setting {Setting}", setting); HttpContext.Response.StatusCode = 401; - Setting = null; + setting = null; } - return Setting; + return setting; } // PUT api//5 [HttpPut("{id}")] - public Setting Put(int id, [FromBody] Setting Setting) + public Setting Put(int id, [FromBody] Setting setting) { - if (ModelState.IsValid && IsAuthorized(Setting.EntityName, Setting.EntityId, PermissionNames.Edit)) + if (ModelState.IsValid && IsAuthorized(setting.EntityName, setting.EntityId, PermissionNames.Edit)) { - Setting = _settings.UpdateSetting(Setting); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Setting Updated {Setting}", Setting); + setting = _settings.UpdateSetting(setting); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Setting Updated {Setting}", setting); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Setting {Setting}", Setting); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update Setting {Setting}", setting); HttpContext.Response.StatusCode = 401; - Setting = null; + setting = null; } - return Setting; + return setting; } // DELETE api//5 @@ -113,15 +112,15 @@ namespace Oqtane.Controllers } } - private bool IsAuthorized(string EntityName, int EntityId, string PermissionName) + private bool IsAuthorized(string entityName, int entityId, string permissionName) { bool authorized = false; - if (EntityName == EntityNames.PageModule) + if (entityName == EntityNames.PageModule) { - EntityName = EntityNames.Module; - EntityId = _pageModules.GetPageModule(EntityId).ModuleId; + entityName = EntityNames.Module; + entityId = _pageModules.GetPageModule(entityId).ModuleId; } - switch (EntityName) + switch (entityName) { case EntityNames.Host: authorized = User.IsInRole(Constants.HostRole); @@ -132,13 +131,13 @@ namespace Oqtane.Controllers case EntityNames.Page: case EntityNames.Module: case EntityNames.Folder: - authorized = _userPermissions.IsAuthorized(User, EntityName, EntityId, PermissionName); + authorized = _userPermissions.IsAuthorized(User, entityName, entityId, permissionName); break; case EntityNames.User: authorized = true; - if (PermissionName == PermissionNames.Edit) + if (permissionName == PermissionNames.Edit) { - authorized = User.IsInRole(Constants.AdminRole) || (_userPermissions.GetUser(User).UserId == EntityId); + authorized = User.IsInRole(Constants.AdminRole) || (_userPermissions.GetUser(User).UserId == entityId); } break; } diff --git a/Oqtane.Server/Controllers/SiteController.cs b/Oqtane.Server/Controllers/SiteController.cs index 47939bf4..ad482652 100644 --- a/Oqtane.Server/Controllers/SiteController.cs +++ b/Oqtane.Server/Controllers/SiteController.cs @@ -1,13 +1,11 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Linq; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -16,15 +14,13 @@ namespace Oqtane.Controllers { private readonly ISiteRepository _sites; private readonly ITenantResolver _tenants; - private readonly IWebHostEnvironment _environment; private readonly ISyncManager _syncManager; private readonly ILogManager _logger; - public SiteController(ISiteRepository sites, ITenantResolver tenants, IWebHostEnvironment environment, ISyncManager syncManager, ILogManager logger) + public SiteController(ISiteRepository sites, ITenantResolver tenants, ISyncManager syncManager, ILogManager logger) { _sites = sites; _tenants = tenants; - _environment = environment; _syncManager = syncManager; _logger = logger; } @@ -46,7 +42,7 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] - public Site Post([FromBody] Site Site) + public Site Post([FromBody] Site site) { if (ModelState.IsValid) { @@ -56,7 +52,7 @@ namespace Oqtane.Controllers // provision initial site during installation authorized = true; Tenant tenant = _tenants.GetTenant(); - Site.TenantId = tenant.TenantId; + site.TenantId = tenant.TenantId; } else { @@ -64,25 +60,25 @@ namespace Oqtane.Controllers } if (authorized) { - Site = _sites.AddSite(Site); - _logger.Log(Site.SiteId, LogLevel.Information, this, LogFunction.Create, "Site Added {Site}", Site); + site = _sites.AddSite(site); + _logger.Log(site.SiteId, LogLevel.Information, this, LogFunction.Create, "Site Added {Site}", site); } } - return Site; + return site; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.HostRole)] - public Site Put(int id, [FromBody] Site Site) + public Site Put(int id, [FromBody] Site site) { if (ModelState.IsValid) { - Site = _sites.UpdateSite(Site); - _syncManager.AddSyncEvent(EntityNames.Site, Site.SiteId); - _logger.Log(Site.SiteId, LogLevel.Information, this, LogFunction.Update, "Site Updated {Site}", Site); + site = _sites.UpdateSite(site); + _syncManager.AddSyncEvent(EntityNames.Site, site.SiteId); + _logger.Log(site.SiteId, LogLevel.Information, this, LogFunction.Update, "Site Updated {Site}", site); } - return Site; + return site; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/TenantController.cs b/Oqtane.Server/Controllers/TenantController.cs index 61ecae8e..aadb2404 100644 --- a/Oqtane.Server/Controllers/TenantController.cs +++ b/Oqtane.Server/Controllers/TenantController.cs @@ -1,10 +1,10 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using System.Collections.Generic; using Oqtane.Shared; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -39,27 +39,27 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.HostRole)] - public Tenant Post([FromBody] Tenant Tenant) + public Tenant Post([FromBody] Tenant tenant) { if (ModelState.IsValid) { - Tenant = _tenants.AddTenant(Tenant); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Tenant Added {TenantId}", Tenant.TenantId); + tenant = _tenants.AddTenant(tenant); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Tenant Added {TenantId}", tenant.TenantId); } - return Tenant; + return tenant; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.HostRole)] - public Tenant Put(int id, [FromBody] Tenant Tenant) + public Tenant Put(int id, [FromBody] Tenant tenant) { if (ModelState.IsValid) { - Tenant = _tenants.UpdateTenant(Tenant); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Tenant Updated {TenantId}", Tenant.TenantId); + tenant = _tenants.UpdateTenant(tenant); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Tenant Updated {TenantId}", tenant.TenantId); } - return Tenant; + return tenant; } // DELETE api//5 diff --git a/Oqtane.Server/Controllers/ThemeController.cs b/Oqtane.Server/Controllers/ThemeController.cs index 6ae226a7..e51275e0 100644 --- a/Oqtane.Server/Controllers/ThemeController.cs +++ b/Oqtane.Server/Controllers/ThemeController.cs @@ -1,14 +1,16 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; -using Oqtane.Repository; using Oqtane.Models; using Microsoft.AspNetCore.Authorization; using Oqtane.Shared; -using Oqtane.Infrastructure; using System.IO; using System.Reflection; using System.Linq; using Microsoft.AspNetCore.Hosting; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; + +// ReSharper disable StringIndexOfIsCultureSpecific.1 namespace Oqtane.Controllers { diff --git a/Oqtane.Server/Controllers/UserController.cs b/Oqtane.Server/Controllers/UserController.cs index c338a0cc..e278f8ae 100644 --- a/Oqtane.Server/Controllers/UserController.cs +++ b/Oqtane.Server/Controllers/UserController.cs @@ -2,17 +2,16 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using System.Linq; using System.Security.Claims; using Oqtane.Shared; -using Oqtane.Infrastructure; using System; -using Microsoft.AspNetCore.Http; using System.Net; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -73,43 +72,39 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] - public async Task Post([FromBody] User User) + public async Task Post([FromBody] User user) { - User user = null; + User newUser = null; if (ModelState.IsValid) { - bool verified = true; - // users created by non-administrators must be verified - if (!base.User.IsInRole(Constants.AdminRole) && User.Username != Constants.HostUser) - { - verified = false; - } + // users created by non-administrators must be verified + bool verified = !(!User.IsInRole(Constants.AdminRole) && user.Username != Constants.HostUser); - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser == null) { identityuser = new IdentityUser(); - identityuser.UserName = User.Username; - identityuser.Email = User.Email; + identityuser.UserName = user.Username; + identityuser.Email = user.Email; identityuser.EmailConfirmed = verified; - var result = await _identityUserManager.CreateAsync(identityuser, User.Password); + var result = await _identityUserManager.CreateAsync(identityuser, user.Password); if (result.Succeeded) { - User.LastLoginOn = null; - User.LastIPAddress = ""; - user = _users.AddUser(User); + user.LastLoginOn = null; + user.LastIPAddress = ""; + newUser = _users.AddUser(user); if (!verified) { Notification notification = new Notification(); - notification.SiteId = User.SiteId; + notification.SiteId = user.SiteId; notification.FromUserId = null; - notification.ToUserId = user.UserId; + notification.ToUserId = newUser.UserId; notification.ToEmail = ""; notification.Subject = "User Account Verification"; string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser); - string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + User.Username + "&token=" + WebUtility.UrlEncode(token); - notification.Body = "Dear " + User.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!"; + string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token); + notification.Body = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!"; notification.ParentId = null; notification.CreatedOn = DateTime.UtcNow; notification.IsDelivered = false; @@ -118,11 +113,11 @@ namespace Oqtane.Controllers } // assign to host role if this is the host user ( initial installation ) - if (User.Username == Constants.HostUser) + if (user.Username == Constants.HostUser) { - int hostroleid = _roles.GetRoles(User.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId; + int hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId; UserRole userrole = new UserRole(); - userrole.UserId = user.UserId; + userrole.UserId = newUser.UserId; userrole.RoleId = hostroleid; userrole.EffectiveDate = null; userrole.ExpiryDate = null; @@ -130,75 +125,79 @@ namespace Oqtane.Controllers } // add folder for user - Folder folder = _folders.GetFolder(User.SiteId, "Users\\"); + Folder folder = _folders.GetFolder(user.SiteId, "Users\\"); if (folder != null) { - _folders.AddFolder(new Folder { SiteId = folder.SiteId, ParentId = folder.FolderId, Name = "My Folder", Path = folder.Path + user.UserId.ToString() + "\\", Order = 1, IsSystem = true, - Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + user.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" + user.UserId.ToString() + "]\"}]" }); + _folders.AddFolder(new Folder { SiteId = folder.SiteId, ParentId = folder.FolderId, Name = "My Folder", Path = folder.Path + newUser.UserId.ToString() + "\\", Order = 1, IsSystem = true, + Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"}]" }); } } } else { - var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, User.Password, false); + var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false); if (result.Succeeded) { - user = _users.GetUser(User.Username); + newUser = _users.GetUser(user.Username); } } - if (user != null && User.Username != Constants.HostUser) + if (newUser != null && user.Username != Constants.HostUser) { // add auto assigned roles to user for site - List roles = _roles.GetRoles(User.SiteId).Where(item => item.IsAutoAssigned == true).ToList(); + List roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList(); foreach (Role role in roles) { UserRole userrole = new UserRole(); - userrole.UserId = user.UserId; + userrole.UserId = newUser.UserId; userrole.RoleId = role.RoleId; userrole.EffectiveDate = null; userrole.ExpiryDate = null; _userRoles.AddUserRole(userrole); } } - user.Password = ""; // remove sensitive information - _logger.Log(User.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", user); + + if (newUser != null) + { + newUser.Password = ""; // remove sensitive information + _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser); + } } - return user; + return newUser; } // PUT api//5 [HttpPut("{id}")] [Authorize] - public async Task Put(int id, [FromBody] User User) + public async Task Put(int id, [FromBody] User user) { if (ModelState.IsValid) { - if (base.User.IsInRole(Constants.AdminRole) || base.User.Identity.Name == User.Username) + if (User.IsInRole(Constants.AdminRole) || User.Identity.Name == user.Username) { - if (User.Password != "") + if (user.Password != "") { - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser != null) { - identityuser.PasswordHash = _identityUserManager.PasswordHasher.HashPassword(identityuser, User.Password); + identityuser.PasswordHash = _identityUserManager.PasswordHasher.HashPassword(identityuser, user.Password); await _identityUserManager.UpdateAsync(identityuser); } } - User = _users.UpdateUser(User); - _syncManager.AddSyncEvent(EntityNames.User, User.UserId); - User.Password = ""; // remove sensitive information - _logger.Log(LogLevel.Information, this, LogFunction.Update, "User Updated {User}", User); + user = _users.UpdateUser(user); + _syncManager.AddSyncEvent(EntityNames.User, user.UserId); + user.Password = ""; // remove sensitive information + _logger.Log(LogLevel.Information, this, LogFunction.Update, "User Updated {User}", user); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update User {User}", User); + _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update User {User}", user); HttpContext.Response.StatusCode = 401; - User = null; + user = null; } } - return User; + return user; } // DELETE api//5?siteid=x @@ -222,147 +221,147 @@ namespace Oqtane.Controllers // POST api//login [HttpPost("login")] - public async Task Login([FromBody] User User, bool SetCookie, bool IsPersistent) + public async Task Login([FromBody] User user, bool setCookie, bool isPersistent) { - User user = new Models.User { Username = User.Username, IsAuthenticated = false }; + User loginUser = new User { Username = user.Username, IsAuthenticated = false }; if (ModelState.IsValid) { - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser != null) { - var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, User.Password, false); + var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false); if (result.Succeeded) { - user = _users.GetUser(identityuser.UserName); - if (user != null) + loginUser = _users.GetUser(identityuser.UserName); + if (loginUser != null) { if (identityuser.EmailConfirmed) { - user.IsAuthenticated = true; - user.LastLoginOn = DateTime.UtcNow; - user.LastIPAddress = HttpContext.Connection.RemoteIpAddress.ToString(); - _users.UpdateUser(user); - _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Login Successful {Username}", User.Username); - if (SetCookie) + loginUser.IsAuthenticated = true; + loginUser.LastLoginOn = DateTime.UtcNow; + loginUser.LastIPAddress = HttpContext.Connection.RemoteIpAddress.ToString(); + _users.UpdateUser(loginUser); + _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Login Successful {Username}", user.Username); + if (setCookie) { - await _identitySignInManager.SignInAsync(identityuser, IsPersistent); + await _identitySignInManager.SignInAsync(identityuser, isPersistent); } } else { - _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Not Verified {Username}", User.Username); + _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Not Verified {Username}", user.Username); } } } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "User Login Failed {Username}", User.Username); + _logger.Log(LogLevel.Error, this, LogFunction.Security, "User Login Failed {Username}", user.Username); } } } - return user; + return loginUser; } // POST api//logout [HttpPost("logout")] [Authorize] - public async Task Logout([FromBody] User User) + public async Task Logout([FromBody] User user) { await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme); - _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Logout {Username}", User.Username); + _logger.Log(LogLevel.Information, this, LogFunction.Security, "User Logout {Username}", user.Username); } // POST api//verify [HttpPost("verify")] - public async Task Verify([FromBody] User User, string token) + public async Task Verify([FromBody] User user, string token) { if (ModelState.IsValid) { - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser != null) { var result = await _identityUserManager.ConfirmEmailAsync(identityuser, token); if (result.Succeeded) { - _logger.Log(LogLevel.Information, this, LogFunction.Security, "Email Verified For {Username}", User.Username); + _logger.Log(LogLevel.Information, this, LogFunction.Security, "Email Verified For {Username}", user.Username); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username}", User.Username); - User = null; + _logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username}", user.Username); + user = null; } } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username}", User.Username); - User = null; + _logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username}", user.Username); + user = null; } } - return User; + return user; } // POST api//forgot [HttpPost("forgot")] - public async Task Forgot([FromBody] User User) + public async Task Forgot([FromBody] User user) { if (ModelState.IsValid) { - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser != null) { Notification notification = new Notification(); - notification.SiteId = User.SiteId; + notification.SiteId = user.SiteId; notification.FromUserId = null; - notification.ToUserId = User.UserId; + notification.ToUserId = user.UserId; notification.ToEmail = ""; notification.Subject = "User Password Reset"; string token = await _identityUserManager.GeneratePasswordResetTokenAsync(identityuser); - string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/reset?name=" + User.Username + "&token=" + WebUtility.UrlEncode(token); - notification.Body = "Dear " + User.DisplayName + ",\n\nPlease Click The Link Displayed Below To Reset Your Password:\n\n" + url + "\n\nThank You!"; + string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/reset?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token); + notification.Body = "Dear " + user.DisplayName + ",\n\nPlease Click The Link Displayed Below To Reset Your Password:\n\n" + url + "\n\nThank You!"; notification.ParentId = null; notification.CreatedOn = DateTime.UtcNow; notification.IsDelivered = false; notification.DeliveredOn = null; _notifications.AddNotification(notification); - _logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset Notification Sent For {Username}", User.Username); + _logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset Notification Sent For {Username}", user.Username); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Notification Failed For {Username}", User.Username); + _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Notification Failed For {Username}", user.Username); } } } // POST api//reset [HttpPost("reset")] - public async Task Reset([FromBody] User User, string token) + public async Task Reset([FromBody] User user, string token) { if (ModelState.IsValid) { - IdentityUser identityuser = await _identityUserManager.FindByNameAsync(User.Username); + IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username); if (identityuser != null && !string.IsNullOrEmpty(token)) { - var result = await _identityUserManager.ResetPasswordAsync(identityuser, token, User.Password); + var result = await _identityUserManager.ResetPasswordAsync(identityuser, token, user.Password); if (result.Succeeded) { - _logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset For {Username}", User.Username); - User.Password = ""; + _logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset For {Username}", user.Username); + user.Password = ""; } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Failed For {Username}", User.Username); - User = null; + _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Failed For {Username}", user.Username); + user = null; } } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Failed For {Username}", User.Username); - User = null; + _logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Failed For {Username}", user.Username); + user = null; } } - return User; + return user; } // GET api//current @@ -382,10 +381,10 @@ namespace Oqtane.Controllers return user; } - private string GetUserRoles(int UserId, int SiteId) + private string GetUserRoles(int userId, int siteId) { string roles = ""; - List userroles = _userRoles.GetUserRoles(UserId, SiteId).ToList(); + List userroles = _userRoles.GetUserRoles(userId, siteId).ToList(); foreach (UserRole userrole in userroles) { roles += userrole.Role.Name + ";"; diff --git a/Oqtane.Server/Controllers/UserRoleController.cs b/Oqtane.Server/Controllers/UserRoleController.cs index 7345beb9..74eaace9 100644 --- a/Oqtane.Server/Controllers/UserRoleController.cs +++ b/Oqtane.Server/Controllers/UserRoleController.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Controllers { @@ -41,29 +41,29 @@ namespace Oqtane.Controllers // POST api/ [HttpPost] [Authorize(Roles = Constants.AdminRole)] - public UserRole Post([FromBody] UserRole UserRole) + public UserRole Post([FromBody] UserRole userRole) { if (ModelState.IsValid) { - UserRole = _userRoles.AddUserRole(UserRole); - _syncManager.AddSyncEvent(EntityNames.User, UserRole.UserId); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "User Role Added {UserRole}", UserRole); + userRole = _userRoles.AddUserRole(userRole); + _syncManager.AddSyncEvent(EntityNames.User, userRole.UserId); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "User Role Added {UserRole}", userRole); } - return UserRole; + return userRole; } // PUT api//5 [HttpPut("{id}")] [Authorize(Roles = Constants.AdminRole)] - public UserRole Put(int id, [FromBody] UserRole UserRole) + public UserRole Put(int id, [FromBody] UserRole userRole) { if (ModelState.IsValid) { - UserRole = _userRoles.UpdateUserRole(UserRole); - _syncManager.AddSyncEvent(EntityNames.User, UserRole.UserId); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "User Role Updated {UserRole}", UserRole); + userRole = _userRoles.UpdateUserRole(userRole); + _syncManager.AddSyncEvent(EntityNames.User, userRole.UserId); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "User Role Updated {UserRole}", userRole); } - return UserRole; + return userRole; } // DELETE api//5 diff --git a/Oqtane.Server/Extensions/AssemblyExtensions.cs b/Oqtane.Server/Extensions/AssemblyExtensions.cs index 7c3bb924..8cb7c39d 100644 --- a/Oqtane.Server/Extensions/AssemblyExtensions.cs +++ b/Oqtane.Server/Extensions/AssemblyExtensions.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +// ReSharper disable once CheckNamespace namespace System.Reflection { public static class AssemblyExtensions diff --git a/Oqtane.Server/Extensions/OqtaneMvcBuilderExtensions.cs b/Oqtane.Server/Extensions/OqtaneMvcBuilderExtensions.cs index 61a3103c..9464e767 100644 --- a/Oqtane.Server/Extensions/OqtaneMvcBuilderExtensions.cs +++ b/Oqtane.Server/Extensions/OqtaneMvcBuilderExtensions.cs @@ -3,6 +3,7 @@ using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; +// ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class OqtaneMvcBuilderExtensions @@ -30,4 +31,4 @@ namespace Microsoft.Extensions.DependencyInjection return mvcBuilder; } } -} \ No newline at end of file +} diff --git a/Oqtane.Server/Extensions/OqtaneServiceCollectionExtensions.cs b/Oqtane.Server/Extensions/OqtaneServiceCollectionExtensions.cs index c32f7194..3911d03b 100644 --- a/Oqtane.Server/Extensions/OqtaneServiceCollectionExtensions.cs +++ b/Oqtane.Server/Extensions/OqtaneServiceCollectionExtensions.cs @@ -8,15 +8,16 @@ using Microsoft.Extensions.Hosting; using Oqtane.Infrastructure; using Oqtane.Modules; +// ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class OqtaneServiceCollectionExtensions { - private static readonly IList _oqtaneModuleAssemblies = new List(); + private static readonly IList OqtaneModuleAssemblies = new List(); private static Assembly[] Assemblies => AppDomain.CurrentDomain.GetAssemblies(); - internal static IEnumerable GetOqtaneModuleAssemblies() => _oqtaneModuleAssemblies; + internal static IEnumerable GetOqtaneModuleAssemblies() => OqtaneModuleAssemblies; public static IServiceCollection AddOqtaneModules(this IServiceCollection services) { @@ -50,15 +51,17 @@ namespace Microsoft.Extensions.DependencyInjection } // dynamically register module services, contexts, and repository classes - var assemblies = Assemblies. - Where(item => item.FullName.StartsWith("Oqtane.") || item.FullName.Contains(".Module.")).ToArray(); + var assemblies = Assemblies.Where(item => item.FullName != null && (item.FullName.StartsWith("Oqtane.") || item.FullName.Contains(".Module."))).ToArray(); foreach (var assembly in assemblies) { var implementationTypes = assembly.GetInterfaces(); foreach (var implementationType in implementationTypes) { - var serviceType = Type.GetType(implementationType.AssemblyQualifiedName.Replace(implementationType.Name, $"I{implementationType.Name}")); - services.AddScoped(serviceType ?? implementationType, implementationType); + if (implementationType.AssemblyQualifiedName != null) + { + var serviceType = Type.GetType(implementationType.AssemblyQualifiedName.Replace(implementationType.Name, $"I{implementationType.Name}")); + services.AddScoped(serviceType ?? implementationType, implementationType); + } } } @@ -91,14 +94,16 @@ namespace Microsoft.Extensions.DependencyInjection private static void LoadAssemblies(string pattern) { - var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); + if (assemblyPath == null) return; + var assembliesFolder = new DirectoryInfo(assemblyPath); // iterate through Oqtane theme assemblies in /bin ( filter is narrow to optimize loading process ) foreach (var file in assembliesFolder.EnumerateFiles($"*.{pattern}.*.dll")) { // check if assembly is already loaded - var assembly = Assemblies.Where(a => a.Location == file.FullName).FirstOrDefault(); + var assembly = Assemblies.FirstOrDefault(a => a.Location == file.FullName); if (assembly == null) { // load assembly from stream to prevent locking file ( as long as dependencies are in /bin they will load as well ) @@ -106,7 +111,7 @@ namespace Microsoft.Extensions.DependencyInjection if (pattern == "Module") { // build a list of module assemblies - _oqtaneModuleAssemblies.Add(assembly); + OqtaneModuleAssemblies.Add(assembly); } } } diff --git a/Oqtane.Server/Infrastructure/InstallationManager.cs b/Oqtane.Server/Infrastructure/InstallationManager.cs index b375d21d..26457c53 100644 --- a/Oqtane.Server/Infrastructure/InstallationManager.cs +++ b/Oqtane.Server/Infrastructure/InstallationManager.cs @@ -7,6 +7,7 @@ using System.Xml; using Oqtane.Shared; using System; using System.Diagnostics; +using Oqtane.Infrastructure.Interfaces; namespace Oqtane.Infrastructure { @@ -21,27 +22,27 @@ namespace Oqtane.Infrastructure _environment = environment; } - public void InstallPackages(string Folders, bool Restart) + public void InstallPackages(string folders, bool restart) { bool install = false; - string binfolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + string binFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); - foreach (string Folder in Folders.Split(',')) + foreach (string folder in folders.Split(',')) { - string folder = Path.Combine(_environment.WebRootPath, Folder); + string sourceFolder = Path.Combine(_environment.WebRootPath, folder); // create folder if it does not exist - if (!Directory.Exists(folder)) + if (!Directory.Exists(sourceFolder)) { - Directory.CreateDirectory(folder); + Directory.CreateDirectory(sourceFolder); } // iterate through packages - foreach (string packagename in Directory.GetFiles(folder, "*.nupkg")) + foreach (string packagename in Directory.GetFiles(sourceFolder, "*.nupkg")) { string name = Path.GetFileNameWithoutExtension(packagename); - string[] segments = name.Split('.'); - name = string.Join('.', segments, 0, segments.Length - 3); + string[] segments = name?.Split('.'); + if (segments != null) name = string.Join('.', segments, 0, segments.Length - 3); // iterate through files using (ZipArchive archive = ZipFile.OpenRead(packagename)) @@ -78,7 +79,7 @@ namespace Oqtane.Infrastructure { case ".pdb": case ".dll": - entry.ExtractToFile(Path.Combine(binfolder, filename), true); + if (binFolder != null) entry.ExtractToFile(Path.Combine(binFolder, filename), true); break; case ".png": case ".jpg": @@ -87,7 +88,7 @@ namespace Oqtane.Infrastructure case ".svg": case ".js": case ".css": - filename = folder + "\\" + entry.FullName.Replace("wwwroot", name).Replace("/", "\\"); + filename = sourceFolder + "\\" + entry.FullName.Replace("wwwroot", name).Replace("/", "\\"); if (!Directory.Exists(Path.GetDirectoryName(filename))) { Directory.CreateDirectory(Path.GetDirectoryName(filename)); @@ -104,7 +105,7 @@ namespace Oqtane.Infrastructure } } - if (install && Restart) + if (install && restart) { // restart application RestartApplication(); @@ -165,26 +166,29 @@ namespace Oqtane.Infrastructure private void FinishUpgrade() { - string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); // check if upgrade application exists - if (File.Exists(Path.Combine(folder, "Oqtane.Upgrade.exe"))) + if (folder == null || !File.Exists(Path.Combine(folder, "Oqtane.Upgrade.exe"))) return; + // run upgrade application + var process = new Process { - // run upgrade application - var process = new Process(); - process.StartInfo.FileName = Path.Combine(folder, "Oqtane.Upgrade.exe"); - process.StartInfo.Arguments = ""; - process.StartInfo.ErrorDialog = false; - process.StartInfo.UseShellExecute = false; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.RedirectStandardOutput = false; - process.StartInfo.RedirectStandardError = false; - process.Start(); - process.Dispose(); + StartInfo = + { + FileName = Path.Combine(folder, "Oqtane.Upgrade.exe"), + Arguments = "", + ErrorDialog = false, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = false, + RedirectStandardError = false + } + }; + process.Start(); + process.Dispose(); - // stop application so upgrade application can proceed - RestartApplication(); - } + // stop application so upgrade application can proceed + RestartApplication(); } public void RestartApplication() diff --git a/Oqtane.Server/Infrastructure/Interfaces/IInstallationManager.cs b/Oqtane.Server/Infrastructure/Interfaces/IInstallationManager.cs index 52afc3f8..a6d0fa90 100644 --- a/Oqtane.Server/Infrastructure/Interfaces/IInstallationManager.cs +++ b/Oqtane.Server/Infrastructure/Interfaces/IInstallationManager.cs @@ -1,8 +1,8 @@ -namespace Oqtane.Infrastructure +namespace Oqtane.Infrastructure.Interfaces { public interface IInstallationManager { - void InstallPackages(string Folders, bool Restart); + void InstallPackages(string folders, bool restart); void UpgradeFramework(); void RestartApplication(); } diff --git a/Oqtane.Server/Infrastructure/Interfaces/ILogManager.cs b/Oqtane.Server/Infrastructure/Interfaces/ILogManager.cs index 0798f86c..920ec59c 100644 --- a/Oqtane.Server/Infrastructure/Interfaces/ILogManager.cs +++ b/Oqtane.Server/Infrastructure/Interfaces/ILogManager.cs @@ -1,15 +1,15 @@ -using Oqtane.Models; +using System; +using Oqtane.Models; using Oqtane.Shared; -using System; -namespace Oqtane.Infrastructure +namespace Oqtane.Infrastructure.Interfaces { public interface ILogManager { - void Log(LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args); - void Log(LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args); - void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args); - void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args); - void Log(Log Log); + void Log(LogLevel level, object @class, LogFunction function, string message, params object[] args); + void Log(LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args); + void Log(int siteId, LogLevel level, object @class, LogFunction function, string message, params object[] args); + void Log(int siteId, LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args); + void Log(Log log); } } diff --git a/Oqtane.Server/Infrastructure/Interfaces/ISyncManager.cs b/Oqtane.Server/Infrastructure/Interfaces/ISyncManager.cs index f5bee6df..3b821f38 100644 --- a/Oqtane.Server/Infrastructure/Interfaces/ISyncManager.cs +++ b/Oqtane.Server/Infrastructure/Interfaces/ISyncManager.cs @@ -1,13 +1,12 @@ -using Oqtane.Models; -using Oqtane.Shared; -using System; +using System; using System.Collections.Generic; +using Oqtane.Models; -namespace Oqtane.Infrastructure +namespace Oqtane.Infrastructure.Interfaces { public interface ISyncManager { - List GetSyncEvents(DateTime LastSyncDate); - void AddSyncEvent(string EntityName, int EntityId); + List GetSyncEvents(DateTime lastSyncDate); + void AddSyncEvent(string entityName, int entityId); } } diff --git a/Oqtane.Server/Infrastructure/Jobs/HostedServiceBase.cs b/Oqtane.Server/Infrastructure/Jobs/HostedServiceBase.cs index 37421b87..35b8b0a9 100644 --- a/Oqtane.Server/Infrastructure/Jobs/HostedServiceBase.cs +++ b/Oqtane.Server/Infrastructure/Jobs/HostedServiceBase.cs @@ -13,7 +13,7 @@ namespace Oqtane.Infrastructure { public abstract class HostedServiceBase : IHostedService, IDisposable { - private Task ExecutingTask; + private Task _executingTask; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly IServiceScopeFactory _serviceScopeFactory; @@ -34,43 +34,43 @@ namespace Oqtane.Infrastructure using (var scope = _serviceScopeFactory.CreateScope()) { // get name of job - string JobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); + string jobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); // load jobs and find current job - IJobRepository Jobs = scope.ServiceProvider.GetRequiredService(); - Job Job = Jobs.GetJobs().Where(item => item.JobType == JobType).FirstOrDefault(); - if (Job != null && Job.IsEnabled && !Job.IsExecuting) + IJobRepository jobs = scope.ServiceProvider.GetRequiredService(); + Job job = jobs.GetJobs().Where(item => item.JobType == jobType).FirstOrDefault(); + if (job != null && job.IsEnabled && !job.IsExecuting) { // set next execution date - if (Job.NextExecution == null) + if (job.NextExecution == null) { - if (Job.StartDate != null) + if (job.StartDate != null) { - Job.NextExecution = Job.StartDate; + job.NextExecution = job.StartDate; } else { - Job.NextExecution = DateTime.UtcNow; + job.NextExecution = DateTime.UtcNow; } } // determine if the job should be run - if (Job.NextExecution <= DateTime.UtcNow && (Job.EndDate == null || Job.EndDate >= DateTime.UtcNow)) + if (job.NextExecution <= DateTime.UtcNow && (job.EndDate == null || job.EndDate >= DateTime.UtcNow)) { - IJobLogRepository JobLogs = scope.ServiceProvider.GetRequiredService(); + IJobLogRepository jobLogs = scope.ServiceProvider.GetRequiredService(); // create a job log entry JobLog log = new JobLog(); - log.JobId = Job.JobId; + log.JobId = job.JobId; log.StartDate = DateTime.UtcNow; log.FinishDate = null; log.Succeeded = false; log.Notes = ""; - log = JobLogs.AddJobLog(log); + log = jobLogs.AddJobLog(log); // update the job to indicate it is running - Job.IsExecuting = true; - Jobs.UpdateJob(Job); + job.IsExecuting = true; + jobs.UpdateJob(job); // execute the job try @@ -86,19 +86,19 @@ namespace Oqtane.Infrastructure // update the job log log.FinishDate = DateTime.UtcNow; - JobLogs.UpdateJobLog(log); + jobLogs.UpdateJobLog(log); // update the job - Job.NextExecution = CalculateNextExecution(Job.NextExecution.Value, Job.Frequency, Job.Interval); - Job.IsExecuting = false; - Jobs.UpdateJob(Job); + job.NextExecution = CalculateNextExecution(job.NextExecution.Value, job.Frequency, job.Interval); + job.IsExecuting = false; + jobs.UpdateJob(job); // trim the job log - List logs = JobLogs.GetJobLogs().Where(item => item.JobId == Job.JobId) + List logs = jobLogs.GetJobLogs().Where(item => item.JobId == job.JobId) .OrderByDescending(item => item.JobLogId).ToList(); - for (int i = logs.Count; i > Job.RetentionHistory; i--) + for (int i = logs.Count; i > job.RetentionHistory; i--) { - JobLogs.DeleteJobLog(logs[i - 1].JobLogId); + jobLogs.DeleteJobLog(logs[i - 1].JobLogId); } } } @@ -115,28 +115,28 @@ namespace Oqtane.Infrastructure } - private DateTime CalculateNextExecution(DateTime NextExecution, string Frequency, int Interval) + private DateTime CalculateNextExecution(DateTime nextExecution, string frequency, int interval) { - switch (Frequency) + switch (frequency) { case "m": // minutes - NextExecution = NextExecution.AddMinutes(Interval); + nextExecution = nextExecution.AddMinutes(interval); break; case "H": // hours - NextExecution = NextExecution.AddHours(Interval); + nextExecution = nextExecution.AddHours(interval); break; case "d": // days - NextExecution = NextExecution.AddDays(Interval); + nextExecution = nextExecution.AddDays(interval); break; case "M": // months - NextExecution = NextExecution.AddMonths(Interval); + nextExecution = nextExecution.AddMonths(interval); break; } - if (NextExecution < DateTime.UtcNow) + if (nextExecution < DateTime.UtcNow) { - NextExecution = DateTime.UtcNow; + nextExecution = DateTime.UtcNow; } - return NextExecution; + return nextExecution; } public Task StartAsync(CancellationToken cancellationToken) @@ -146,14 +146,14 @@ namespace Oqtane.Infrastructure // set IsExecuting to false in case this job was forcefully terminated previously using (var scope = _serviceScopeFactory.CreateScope()) { - string JobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); - IJobRepository Jobs = scope.ServiceProvider.GetRequiredService(); - Job Job = Jobs.GetJobs().Where(item => item.JobType == JobType).FirstOrDefault(); - if (Job != null) + string jobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName); + IJobRepository jobs = scope.ServiceProvider.GetRequiredService(); + Job job = jobs.GetJobs().Where(item => item.JobType == jobType).FirstOrDefault(); + if (job != null) { - Job.IsStarted = true; - Job.IsExecuting = false; - Jobs.UpdateJob(Job); + job.IsStarted = true; + job.IsExecuting = false; + jobs.UpdateJob(job); } } } @@ -162,19 +162,19 @@ namespace Oqtane.Infrastructure // can occur during the initial installation as there is no DBContext } - ExecutingTask = ExecuteAsync(_cancellationTokenSource.Token); + _executingTask = ExecuteAsync(_cancellationTokenSource.Token); - if (ExecutingTask.IsCompleted) + if (_executingTask.IsCompleted) { - return ExecutingTask; + return _executingTask; } return Task.CompletedTask; } - public async Task StopAsync(CancellationToken CancellationToken) + public async Task StopAsync(CancellationToken cancellationToken) { - if (ExecutingTask == null) + if (_executingTask == null) { return; } @@ -185,7 +185,7 @@ namespace Oqtane.Infrastructure } finally { - await Task.WhenAny(ExecutingTask, Task.Delay(Timeout.Infinite, CancellationToken)); + await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)); } } diff --git a/Oqtane.Server/Infrastructure/Jobs/NotificationJob.cs b/Oqtane.Server/Infrastructure/Jobs/NotificationJob.cs index e693924d..eea37e47 100644 --- a/Oqtane.Server/Infrastructure/Jobs/NotificationJob.cs +++ b/Oqtane.Server/Infrastructure/Jobs/NotificationJob.cs @@ -14,34 +14,34 @@ namespace Oqtane.Infrastructure { // JobType = "Oqtane.Infrastructure.NotificationJob, Oqtane.Server" - public NotificationJob(IServiceScopeFactory ServiceScopeFactory) : base(ServiceScopeFactory) {} + public NotificationJob(IServiceScopeFactory serviceScopeFactory) : base(serviceScopeFactory) {} public override string ExecuteJob(IServiceProvider provider) { string log = ""; // iterate through aliases in this installation - var Aliases = provider.GetRequiredService(); - List aliases = Aliases.GetAliases().ToList(); + var aliasRepository = provider.GetRequiredService(); + List aliases = aliasRepository.GetAliases().ToList(); foreach (Alias alias in aliases) { // use the SiteState to set the Alias explicitly so the tenant can be resolved - var sitestate = provider.GetRequiredService(); - sitestate.Alias = alias; + var siteState = provider.GetRequiredService(); + siteState.Alias = alias; // get services which require tenant resolution - var Sites = provider.GetRequiredService(); - var Settings = provider.GetRequiredService(); - var Notifications = provider.GetRequiredService(); + var siteRepository = provider.GetRequiredService(); + var settingRepository = provider.GetRequiredService(); + var notificationRepository = provider.GetRequiredService(); // iterate through sites - List sites = Sites.GetSites().ToList(); + List sites = siteRepository.GetSites().ToList(); foreach (Site site in sites) { log += "Processing Notifications For Site: " + site.Name + "\n\n"; // get site settings - List sitesettings = Settings.GetSettings("Site", site.SiteId).ToList(); + List sitesettings = settingRepository.GetSettings("Site", site.SiteId).ToList(); Dictionary settings = GetSettings(sitesettings); if (settings.ContainsKey("SMTPHost") && settings["SMTPHost"] != "") { @@ -61,7 +61,7 @@ namespace Oqtane.Infrastructure // iterate through notifications int sent = 0; - List notifications = Notifications.GetNotifications(site.SiteId, -1, -1).ToList(); + List notifications = notificationRepository.GetNotifications(site.SiteId, -1, -1).ToList(); foreach (Notification notification in notifications) { MailMessage mailMessage = new MailMessage(); @@ -75,7 +75,7 @@ namespace Oqtane.Infrastructure { mailMessage.Body = "From: " + site.Name + "\n"; } - mailMessage.Body += "Sent: " + notification.CreatedOn.ToString() + "\n"; + mailMessage.Body += "Sent: " + notification.CreatedOn + "\n"; if (notification.ToUserId != null) { mailMessage.To.Add(new MailAddress(notification.ToUser.Email, notification.ToUser.DisplayName)); @@ -96,15 +96,15 @@ namespace Oqtane.Infrastructure sent = sent++; notification.IsDelivered = true; notification.DeliveredOn = DateTime.UtcNow; - Notifications.UpdateNotification(notification); + notificationRepository.UpdateNotification(notification); } catch (Exception ex) { // error - log += ex.Message.ToString() + "\n\n"; + log += ex.Message + "\n\n"; } } - log += "Notifications Delivered: " + sent.ToString() + "\n\n"; + log += "Notifications Delivered: " + sent + "\n\n"; } else { @@ -117,10 +117,10 @@ namespace Oqtane.Infrastructure } - private Dictionary GetSettings(List Settings) + private Dictionary GetSettings(List settings) { Dictionary dictionary = new Dictionary(); - foreach (Setting setting in Settings.OrderBy(item => item.SettingName).ToList()) + foreach (Setting setting in settings.OrderBy(item => item.SettingName).ToList()) { dictionary.Add(setting.SettingName, setting.SettingValue); } diff --git a/Oqtane.Server/Infrastructure/LogManager.cs b/Oqtane.Server/Infrastructure/LogManager.cs index 195e9c5b..11b17eb5 100644 --- a/Oqtane.Server/Infrastructure/LogManager.cs +++ b/Oqtane.Server/Infrastructure/LogManager.cs @@ -2,11 +2,14 @@ using System; using Oqtane.Models; using System.Text.Json; -using Oqtane.Repository; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; using System.Collections.Generic; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; using Oqtane.Security; +// ReSharper disable StringIndexOfIsCultureSpecific.2 +// ReSharper disable StringIndexOfIsCultureSpecific.1 namespace Oqtane.Infrastructure { @@ -27,25 +30,25 @@ namespace Oqtane.Infrastructure _accessor = accessor; } - public void Log(LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args) + public void Log(LogLevel level, object @class, LogFunction function, string message, params object[] args) { - Log(-1, Level, Class.GetType().AssemblyQualifiedName, Function, null, Message, Args); + Log(-1, level, @class.GetType().AssemblyQualifiedName, function, null, message, args); } - public void Log(LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args) + public void Log(LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args) { - Log(-1, Level, Class.GetType().AssemblyQualifiedName, Function, Exception, Message, Args); + Log(-1, level, @class.GetType().AssemblyQualifiedName, function, exception, message, args); } - public void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, string Message, params object[] Args) + public void Log(int siteId, LogLevel level, object @class, LogFunction function, string message, params object[] args) { - Log(SiteId, Level, Class.GetType().AssemblyQualifiedName, Function, null, Message, Args); + Log(siteId, level, @class.GetType().AssemblyQualifiedName, function, null, message, args); } - public void Log(int SiteId, LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args) + public void Log(int siteId, LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args) { Log log = new Log(); - if (SiteId == -1) + if (siteId == -1) { log.SiteId = null; Alias alias = _tenantResolver.GetAlias(); @@ -56,7 +59,7 @@ namespace Oqtane.Infrastructure } else { - log.SiteId = SiteId; + log.SiteId = siteId; } log.PageId = null; log.ModuleId = null; @@ -69,10 +72,10 @@ namespace Oqtane.Infrastructure HttpRequest request = _accessor.HttpContext.Request; if (request != null) { - log.Url = request.Scheme.ToString() + "://" + request.Host.ToString() + request.Path.ToString() + request.QueryString.ToString(); + log.Url = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}"; } - Type type = Type.GetType(Class.ToString()); + Type type = @class.GetType(); if (type != null) { log.Category = type.AssemblyQualifiedName; @@ -80,20 +83,20 @@ namespace Oqtane.Infrastructure } else { - log.Category = Class.ToString(); + log.Category = @class.ToString(); log.Feature = log.Category; } - log.Function = Enum.GetName(typeof(LogFunction), Function); - log.Level = Enum.GetName(typeof(LogLevel), Level); - if (Exception != null) + log.Function = Enum.GetName(typeof(LogFunction), function); + log.Level = Enum.GetName(typeof(LogLevel), level); + if (exception != null) { - log.Exception = Exception.ToString(); + log.Exception = exception.ToString(); } - log.Message = Message; + log.Message = message; log.MessageTemplate = ""; try { - log.Properties = JsonSerializer.Serialize(Args); + log.Properties = JsonSerializer.Serialize(args); } catch // serialization error occurred { @@ -102,7 +105,7 @@ namespace Oqtane.Infrastructure Log(log); } - public void Log(Log Log) + public void Log(Log log) { LogLevel minlevel = LogLevel.Information; var section = _config.GetSection("Logging:LogLevel:Default"); @@ -111,15 +114,15 @@ namespace Oqtane.Infrastructure minlevel = Enum.Parse(_config.GetSection("Logging:LogLevel:Default").ToString()); } - if (Enum.Parse(Log.Level) >= minlevel) + if (Enum.Parse(log.Level) >= minlevel) { - Log.LogDate = DateTime.UtcNow; - Log.Server = Environment.MachineName; - Log.MessageTemplate = Log.Message; - Log = ProcessStructuredLog(Log); + log.LogDate = DateTime.UtcNow; + log.Server = Environment.MachineName; + log.MessageTemplate = log.Message; + log = ProcessStructuredLog(log); try { - _logs.AddLog(Log); + _logs.AddLog(log); } catch { @@ -128,16 +131,16 @@ namespace Oqtane.Infrastructure } } - private Log ProcessStructuredLog(Log Log) + private Log ProcessStructuredLog(Log log) { try { - string message = Log.Message; + string message = log.Message; string properties = ""; - if (!string.IsNullOrEmpty(message) && message.Contains("{") && message.Contains("}") && !string.IsNullOrEmpty(Log.Properties)) + if (!string.IsNullOrEmpty(message) && message.Contains("{") && message.Contains("}") && !string.IsNullOrEmpty(log.Properties)) { // get the named holes in the message and replace values - object[] values = JsonSerializer.Deserialize(Log.Properties); + object[] values = JsonSerializer.Deserialize(log.Properties); List names = new List(); int index = message.IndexOf("{"); while (index != -1) @@ -160,28 +163,28 @@ namespace Oqtane.Infrastructure index = message.IndexOf("{", index + 1); } // rebuild properties into dictionary - Dictionary propertydictionary = new Dictionary(); + Dictionary propertyDictionary = new Dictionary(); for (int i = 0; i < values.Length; i++) { if (i < names.Count) { - propertydictionary.Add(names[i], values[i]); + propertyDictionary.Add(names[i], values[i]); } else { - propertydictionary.Add("Property" + i.ToString(), values[i]); + propertyDictionary.Add("Property" + i.ToString(), values[i]); } } - properties = JsonSerializer.Serialize(propertydictionary); + properties = JsonSerializer.Serialize(propertyDictionary); } - Log.Message = message; - Log.Properties = properties; + log.Message = message; + log.Properties = properties; } catch { - Log.Properties = ""; + log.Properties = ""; } - return Log; + return log; } } -} \ No newline at end of file +} diff --git a/Oqtane.Server/Infrastructure/SyncManager.cs b/Oqtane.Server/Infrastructure/SyncManager.cs index b9495e22..7828bbc3 100644 --- a/Oqtane.Server/Infrastructure/SyncManager.cs +++ b/Oqtane.Server/Infrastructure/SyncManager.cs @@ -1,20 +1,21 @@ using Microsoft.Extensions.DependencyInjection; using Oqtane.Models; -using Oqtane.Repository; using System; using System.Collections.Generic; using System.Linq; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; namespace Oqtane.Infrastructure { public class SyncManager : ISyncManager { - private readonly IServiceScopeFactory ServiceScopeFactory; + private readonly IServiceScopeFactory _serviceScopeFactory; private List SyncEvents { get; set; } - public SyncManager(IServiceScopeFactory ServiceScopeFactory) + public SyncManager(IServiceScopeFactory serviceScopeFactory) { - this.ServiceScopeFactory = ServiceScopeFactory; + this._serviceScopeFactory = serviceScopeFactory; SyncEvents = new List(); } @@ -22,21 +23,21 @@ namespace Oqtane.Infrastructure { get { - using (var scope = ServiceScopeFactory.CreateScope()) + using (var scope = _serviceScopeFactory.CreateScope()) { return scope.ServiceProvider.GetRequiredService().GetTenant().TenantId; } } } - public List GetSyncEvents(DateTime LastSyncDate) + public List GetSyncEvents(DateTime lastSyncDate) { - return SyncEvents.Where(item => item.TenantId == TenantId && item.ModifiedOn >= LastSyncDate).ToList(); + return SyncEvents.Where(item => item.TenantId == TenantId && item.ModifiedOn >= lastSyncDate).ToList(); } - public void AddSyncEvent(string EntityName, int EntityId) + public void AddSyncEvent(string entityName, int entityId) { - SyncEvents.Add(new SyncEvent { TenantId = TenantId, EntityName = EntityName, EntityId = EntityId, ModifiedOn = DateTime.UtcNow }); + SyncEvents.Add(new SyncEvent { TenantId = TenantId, EntityName = entityName, EntityId = entityId, ModifiedOn = DateTime.UtcNow }); // trim sync events SyncEvents.RemoveAll(item => item.ModifiedOn < DateTime.UtcNow.AddHours(-1)); } diff --git a/Oqtane.Server/Modules/HtmlText/Controllers/HtmlTextController.cs b/Oqtane.Server/Modules/HtmlText/Controllers/HtmlTextController.cs index bb8db89c..39885c81 100644 --- a/Oqtane.Server/Modules/HtmlText/Controllers/HtmlTextController.cs +++ b/Oqtane.Server/Modules/HtmlText/Controllers/HtmlTextController.cs @@ -3,10 +3,10 @@ using Microsoft.AspNetCore.Authorization; using Oqtane.Modules.HtmlText.Models; using Oqtane.Modules.HtmlText.Repository; using Microsoft.AspNetCore.Http; -using Oqtane.Infrastructure; using Oqtane.Shared; using System; using System.Collections.Generic; +using Oqtane.Infrastructure.Interfaces; namespace Oqtane.Modules.HtmlText.Controllers { @@ -35,11 +35,11 @@ namespace Oqtane.Modules.HtmlText.Controllers var list = new List(); try { - HtmlTextInfo HtmlText = null; + HtmlTextInfo htmlText = null; if (_entityId == id) { - HtmlText = _htmlText.GetHtmlText(id); - list.Add(HtmlText); + htmlText = _htmlText.GetHtmlText(id); + list.Add(htmlText); } } catch (Exception ex) @@ -53,16 +53,16 @@ namespace Oqtane.Modules.HtmlText.Controllers // POST api/ [HttpPost] [Authorize(Policy = "EditModule")] - public HtmlTextInfo Post([FromBody] HtmlTextInfo HtmlText) + public HtmlTextInfo Post([FromBody] HtmlTextInfo htmlText) { try { - if (ModelState.IsValid && HtmlText.ModuleId == _entityId) + if (ModelState.IsValid && htmlText.ModuleId == _entityId) { - HtmlText = _htmlText.AddHtmlText(HtmlText); - _logger.Log(LogLevel.Information, this, LogFunction.Create, "Html/Text Added {HtmlText}", HtmlText); + htmlText = _htmlText.AddHtmlText(htmlText); + _logger.Log(LogLevel.Information, this, LogFunction.Create, "Html/Text Added {HtmlText}", htmlText); } - return HtmlText; + return htmlText; } catch (Exception ex) { @@ -74,16 +74,16 @@ namespace Oqtane.Modules.HtmlText.Controllers // PUT api//5 [HttpPut("{id}")] [Authorize(Policy = "EditModule")] - public HtmlTextInfo Put(int id, [FromBody] HtmlTextInfo HtmlText) + public HtmlTextInfo Put(int id, [FromBody] HtmlTextInfo htmlText) { try { - if (ModelState.IsValid && HtmlText.ModuleId == _entityId) + if (ModelState.IsValid && htmlText.ModuleId == _entityId) { - HtmlText = _htmlText.UpdateHtmlText(HtmlText); - _logger.Log(LogLevel.Information, this, LogFunction.Update, "Html/Text Updated {HtmlText}", HtmlText); + htmlText = _htmlText.UpdateHtmlText(htmlText); + _logger.Log(LogLevel.Information, this, LogFunction.Update, "Html/Text Updated {HtmlText}", htmlText); } - return HtmlText; + return htmlText; } catch (Exception ex) { diff --git a/Oqtane.Server/Modules/HtmlText/Manager/HtmlTextManager.cs b/Oqtane.Server/Modules/HtmlText/Manager/HtmlTextManager.cs index 0d87934d..f37ac523 100644 --- a/Oqtane.Server/Modules/HtmlText/Manager/HtmlTextManager.cs +++ b/Oqtane.Server/Modules/HtmlText/Manager/HtmlTextManager.cs @@ -14,10 +14,10 @@ namespace Oqtane.Modules.HtmlText.Manager _htmlTexts = htmltexts; } - public string ExportModule(Module Module) + public string ExportModule(Module module) { string content = ""; - HtmlTextInfo htmltext = _htmlTexts.GetHtmlText(Module.ModuleId); + HtmlTextInfo htmltext = _htmlTexts.GetHtmlText(module.ModuleId); if (htmltext != null) { content = WebUtility.HtmlEncode(htmltext.Content); @@ -25,20 +25,20 @@ namespace Oqtane.Modules.HtmlText.Manager return content; } - public void ImportModule(Module Module, string Content, string Version) + public void ImportModule(Module module, string content, string version) { - Content = WebUtility.HtmlDecode(Content); - HtmlTextInfo htmltext = _htmlTexts.GetHtmlText(Module.ModuleId); + content = WebUtility.HtmlDecode(content); + HtmlTextInfo htmltext = _htmlTexts.GetHtmlText(module.ModuleId); if (htmltext != null) { - htmltext.Content = Content; + htmltext.Content = content; _htmlTexts.UpdateHtmlText(htmltext); } else { htmltext = new HtmlTextInfo(); - htmltext.ModuleId = Module.ModuleId; - htmltext.Content = Content; + htmltext.ModuleId = module.ModuleId; + htmltext.Content = content; _htmlTexts.AddHtmlText(htmltext); } } diff --git a/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextContext.cs b/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextContext.cs index 2ff3e6d2..70cd2065 100644 --- a/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextContext.cs +++ b/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextContext.cs @@ -9,7 +9,7 @@ namespace Oqtane.Modules.HtmlText.Repository { public virtual DbSet HtmlText { get; set; } - public HtmlTextContext(ITenantResolver TenantResolver, IHttpContextAccessor accessor) : base(TenantResolver, accessor) + public HtmlTextContext(ITenantResolver tenantResolver, IHttpContextAccessor accessor) : base(tenantResolver, accessor) { // ContextBase handles multi-tenant database connections } diff --git a/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextRepository.cs b/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextRepository.cs index 144ea1e5..c97b0de7 100644 --- a/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextRepository.cs +++ b/Oqtane.Server/Modules/HtmlText/Repository/HtmlTextRepository.cs @@ -13,59 +13,31 @@ namespace Oqtane.Modules.HtmlText.Repository _db = context; } - public HtmlTextInfo GetHtmlText(int ModuleId) + public HtmlTextInfo GetHtmlText(int moduleId) { - try - { - return _db.HtmlText.Where(item => item.ModuleId == ModuleId).FirstOrDefault(); - } - catch - { - throw; - } + return _db.HtmlText.FirstOrDefault(item => item.ModuleId == moduleId); } - public HtmlTextInfo AddHtmlText(HtmlTextInfo HtmlText) + public HtmlTextInfo AddHtmlText(HtmlTextInfo htmlText) { - try - { - _db.HtmlText.Add(HtmlText); - _db.SaveChanges(); - return HtmlText; - } - catch - { - throw; - } + _db.HtmlText.Add(htmlText); + _db.SaveChanges(); + return htmlText; } - public HtmlTextInfo UpdateHtmlText(HtmlTextInfo HtmlText) + public HtmlTextInfo UpdateHtmlText(HtmlTextInfo htmlText) { - try - { - _db.Entry(HtmlText).State = EntityState.Modified; - _db.SaveChanges(); - return HtmlText; - } - catch - { - throw; - } + _db.Entry(htmlText).State = EntityState.Modified; + _db.SaveChanges(); + return htmlText; } - public void DeleteHtmlText(int ModuleId) + public void DeleteHtmlText(int moduleId) { - try - { - HtmlTextInfo HtmlText = _db.HtmlText.Where(item => item.ModuleId == ModuleId).FirstOrDefault(); - _db.HtmlText.Remove(HtmlText); - _db.SaveChanges(); - } - catch - { - throw; - } + HtmlTextInfo htmlText = _db.HtmlText.FirstOrDefault(item => item.ModuleId == moduleId); + if (htmlText != null) _db.HtmlText.Remove(htmlText); + _db.SaveChanges(); } } } diff --git a/Oqtane.Server/Modules/HtmlText/Repository/IHtmlTextRepository.cs b/Oqtane.Server/Modules/HtmlText/Repository/IHtmlTextRepository.cs index 33e368c4..cbe5d0e4 100644 --- a/Oqtane.Server/Modules/HtmlText/Repository/IHtmlTextRepository.cs +++ b/Oqtane.Server/Modules/HtmlText/Repository/IHtmlTextRepository.cs @@ -1,13 +1,12 @@ -using System.Collections.Generic; -using Oqtane.Modules.HtmlText.Models; +using Oqtane.Modules.HtmlText.Models; namespace Oqtane.Modules.HtmlText.Repository { public interface IHtmlTextRepository { - HtmlTextInfo GetHtmlText(int ModuleId); - HtmlTextInfo AddHtmlText(HtmlTextInfo HtmlText); - HtmlTextInfo UpdateHtmlText(HtmlTextInfo HtmlText); - void DeleteHtmlText(int ModuleId); + HtmlTextInfo GetHtmlText(int moduleId); + HtmlTextInfo AddHtmlText(HtmlTextInfo htmlText); + HtmlTextInfo UpdateHtmlText(HtmlTextInfo htmlText); + void DeleteHtmlText(int moduleId); } } diff --git a/Oqtane.Server/Modules/IPortable.cs b/Oqtane.Server/Modules/IPortable.cs index 871c3045..b4c89735 100644 --- a/Oqtane.Server/Modules/IPortable.cs +++ b/Oqtane.Server/Modules/IPortable.cs @@ -6,8 +6,8 @@ namespace Oqtane.Modules { // You Must Set The "ServerAssemblyName" In Your IModule Interface - string ExportModule(Module Module); + string ExportModule(Module module); - void ImportModule(Module Module, string Content, string Version); + void ImportModule(Module module, string content, string version); } } diff --git a/Oqtane.Server/Pages/_Host.cshtml b/Oqtane.Server/Pages/_Host.cshtml index c1c7782f..c5a90e79 100644 --- a/Oqtane.Server/Pages/_Host.cshtml +++ b/Oqtane.Server/Pages/_Host.cshtml @@ -1,7 +1,6 @@ @page "/" @namespace Oqtane.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers -@using Oqtane.Client diff --git a/Oqtane.Server/Program.cs b/Oqtane.Server/Program.cs index ca26b836..89bb47b3 100644 --- a/Oqtane.Server/Program.cs +++ b/Oqtane.Server/Program.cs @@ -1,11 +1,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -using Microsoft.AspNetCore.Blazor.Hosting; -// used by client-side Blazor -using Microsoft.Extensions.Configuration; -using Microsoft.AspNetCore; -namespace Oqtane.Server +// used by client-side Blazor + +namespace Oqtane { public class Program { diff --git a/Oqtane.Server/Repository/AliasRepository.cs b/Oqtane.Server/Repository/AliasRepository.cs index fe16d4d9..ccb26681 100644 --- a/Oqtane.Server/Repository/AliasRepository.cs +++ b/Oqtane.Server/Repository/AliasRepository.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; -using System; +using Oqtane.Models; namespace Oqtane.Repository { @@ -27,30 +27,30 @@ namespace Oqtane.Repository }); } - public Alias AddAlias(Alias Alias) + public Alias AddAlias(Alias alias) { - _db.Alias.Add(Alias); + _db.Alias.Add(alias); _db.SaveChanges(); _cache.Remove("aliases"); - return Alias; + return alias; } - public Alias UpdateAlias(Alias Alias) + public Alias UpdateAlias(Alias alias) { - _db.Entry(Alias).State = EntityState.Modified; + _db.Entry(alias).State = EntityState.Modified; _db.SaveChanges(); _cache.Remove("aliases"); - return Alias; + return alias; } - public Alias GetAlias(int AliasId) + public Alias GetAlias(int aliasId) { - return _db.Alias.Find(AliasId); + return _db.Alias.Find(aliasId); } - public void DeleteAlias(int AliasId) + public void DeleteAlias(int aliasId) { - Alias alias = _db.Alias.Find(AliasId); + Alias alias = _db.Alias.Find(aliasId); _db.Alias.Remove(alias); _cache.Remove("aliases"); _db.SaveChanges(); diff --git a/Oqtane.Server/Repository/Context/DBContextBase.cs b/Oqtane.Server/Repository/Context/DBContextBase.cs index 405d43ed..e6aceed9 100644 --- a/Oqtane.Server/Repository/Context/DBContextBase.cs +++ b/Oqtane.Server/Repository/Context/DBContextBase.cs @@ -1,10 +1,10 @@ -using Microsoft.AspNetCore.Http; +using System; +using System.Linq; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Oqtane.Models; -using System; -using System.Linq; namespace Oqtane.Repository { @@ -53,7 +53,7 @@ namespace Oqtane.Repository foreach(var item in created) { - if (item.Entity is IAuditable entity) + if (item.Entity is IAuditable) { item.CurrentValues[nameof(IAuditable.CreatedBy)] = username; item.CurrentValues[nameof(IAuditable.CreatedOn)] = date; @@ -65,13 +65,13 @@ namespace Oqtane.Repository foreach (var item in modified) { - if (item.Entity is IAuditable entity) + if (item.Entity is IAuditable) { item.CurrentValues[nameof(IAuditable.ModifiedBy)] = username; item.CurrentValues[nameof(IAuditable.ModifiedOn)] = date; } - if (item.Entity is IDeletable deleted && item.State != EntityState.Added) + if (item.Entity is IDeletable && item.State != EntityState.Added) { if ((bool)item.CurrentValues[nameof(IDeletable.IsDeleted)] && !item.GetDatabaseValues().GetValue(nameof(IDeletable.IsDeleted))) diff --git a/Oqtane.Server/Repository/Context/MasterDBContext.cs b/Oqtane.Server/Repository/Context/MasterDBContext.cs index e120ff7d..65312819 100644 --- a/Oqtane.Server/Repository/Context/MasterDBContext.cs +++ b/Oqtane.Server/Repository/Context/MasterDBContext.cs @@ -1,8 +1,8 @@ -using Microsoft.AspNetCore.Http; +using System; +using System.Linq; +using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Oqtane.Models; -using System; -using System.Linq; namespace Oqtane.Repository { @@ -37,7 +37,7 @@ namespace Oqtane.Repository foreach (var item in created) { - if (item.Entity is IAuditable entity) + if (item.Entity is IAuditable) { item.CurrentValues[nameof(IAuditable.CreatedBy)] = username; item.CurrentValues[nameof(IAuditable.CreatedOn)] = date; @@ -49,7 +49,7 @@ namespace Oqtane.Repository foreach (var item in modified) { - if (item.Entity is IAuditable entity) + if (item.Entity is IAuditable) { item.CurrentValues[nameof(IAuditable.ModifiedBy)] = username; item.CurrentValues[nameof(IAuditable.ModifiedOn)] = date; diff --git a/Oqtane.Server/Repository/Context/TenantDBContext.cs b/Oqtane.Server/Repository/Context/TenantDBContext.cs index c90f8538..be085b20 100644 --- a/Oqtane.Server/Repository/Context/TenantDBContext.cs +++ b/Oqtane.Server/Repository/Context/TenantDBContext.cs @@ -21,7 +21,7 @@ namespace Oqtane.Repository public virtual DbSet Folder { get; set; } public virtual DbSet File { get; set; } - public TenantDBContext(ITenantResolver TenantResolver, IHttpContextAccessor accessor) : base(TenantResolver, accessor) + public TenantDBContext(ITenantResolver tenantResolver, IHttpContextAccessor accessor) : base(tenantResolver, accessor) { // DBContextBase handles multi-tenant database connections } diff --git a/Oqtane.Server/Repository/FileRepository.cs b/Oqtane.Server/Repository/FileRepository.cs index 5b67bb4a..fe5d3380 100644 --- a/Oqtane.Server/Repository/FileRepository.cs +++ b/Oqtane.Server/Repository/FileRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -16,34 +16,34 @@ namespace Oqtane.Repository _permissions = permissions; } - public IEnumerable GetFiles(int FolderId) + public IEnumerable GetFiles(int folderId) { - IEnumerable permissions = _permissions.GetPermissions("Folder", FolderId).ToList(); - IEnumerable files = _db.File.Where(item => item.FolderId == FolderId).Include(item => item.Folder); + IEnumerable permissions = _permissions.GetPermissions("Folder", folderId).ToList(); + IEnumerable files = _db.File.Where(item => item.FolderId == folderId).Include(item => item.Folder); foreach (File file in files) { - file.Folder.Permissions = _permissions.EncodePermissions(FolderId, permissions); + file.Folder.Permissions = _permissions.EncodePermissions(folderId, permissions); } return files; } - public File AddFile(File File) + public File AddFile(File file) { - _db.File.Add(File); + _db.File.Add(file); _db.SaveChanges(); - return File; + return file; } - public File UpdateFile(File File) + public File UpdateFile(File file) { - _db.Entry(File).State = EntityState.Modified; + _db.Entry(file).State = EntityState.Modified; _db.SaveChanges(); - return File; + return file; } - public File GetFile(int FileId) + public File GetFile(int fileId) { - File file = _db.File.Where(item => item.FileId == FileId).Include(item => item.Folder).FirstOrDefault(); + File file = _db.File.Where(item => item.FileId == fileId).Include(item => item.Folder).FirstOrDefault(); if (file != null) { IEnumerable permissions = _permissions.GetPermissions("Folder", file.FolderId).ToList(); @@ -52,10 +52,10 @@ namespace Oqtane.Repository return file; } - public void DeleteFile(int FileId) + public void DeleteFile(int fileId) { - File File = _db.File.Find(FileId); - _db.File.Remove(File); + File file = _db.File.Find(fileId); + _db.File.Remove(file); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/FolderRepository.cs b/Oqtane.Server/Repository/FolderRepository.cs index f4a67d5a..b3d6f4e3 100644 --- a/Oqtane.Server/Repository/FolderRepository.cs +++ b/Oqtane.Server/Repository/FolderRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -16,10 +16,10 @@ namespace Oqtane.Repository _permissions = permissions; } - public IEnumerable GetFolders(int SiteId) + public IEnumerable GetFolders(int siteId) { - IEnumerable permissions = _permissions.GetPermissions(SiteId, "Folder").ToList(); - IEnumerable folders = _db.Folder.Where(item => item.SiteId == SiteId); + IEnumerable permissions = _permissions.GetPermissions(siteId, "Folder").ToList(); + IEnumerable folders = _db.Folder.Where(item => item.SiteId == siteId); foreach(Folder folder in folders) { folder.Permissions = _permissions.EncodePermissions(folder.FolderId, permissions); @@ -27,25 +27,25 @@ namespace Oqtane.Repository return folders; } - public Folder AddFolder(Folder Folder) + public Folder AddFolder(Folder folder) { - _db.Folder.Add(Folder); + _db.Folder.Add(folder); _db.SaveChanges(); - _permissions.UpdatePermissions(Folder.SiteId, "Folder", Folder.FolderId, Folder.Permissions); - return Folder; + _permissions.UpdatePermissions(folder.SiteId, "Folder", folder.FolderId, folder.Permissions); + return folder; } - public Folder UpdateFolder(Folder Folder) + public Folder UpdateFolder(Folder folder) { - _db.Entry(Folder).State = EntityState.Modified; + _db.Entry(folder).State = EntityState.Modified; _db.SaveChanges(); - _permissions.UpdatePermissions(Folder.SiteId, "Folder", Folder.FolderId, Folder.Permissions); - return Folder; + _permissions.UpdatePermissions(folder.SiteId, "Folder", folder.FolderId, folder.Permissions); + return folder; } - public Folder GetFolder(int FolderId) + public Folder GetFolder(int folderId) { - Folder folder = _db.Folder.Find(FolderId); + Folder folder = _db.Folder.Find(folderId); if (folder != null) { IEnumerable permissions = _permissions.GetPermissions("Folder", folder.FolderId).ToList(); @@ -54,9 +54,9 @@ namespace Oqtane.Repository return folder; } - public Folder GetFolder(int SiteId, string Path) + public Folder GetFolder(int siteId, string path) { - Folder folder = _db.Folder.Where(item => item.SiteId == SiteId && item.Path == Path).FirstOrDefault(); + Folder folder = _db.Folder.Where(item => item.SiteId == siteId && item.Path == path).FirstOrDefault(); if (folder != null) { IEnumerable permissions = _permissions.GetPermissions("Folder", folder.FolderId).ToList(); @@ -65,11 +65,11 @@ namespace Oqtane.Repository return folder; } - public void DeleteFolder(int FolderId) + public void DeleteFolder(int folderId) { - Folder Folder = _db.Folder.Find(FolderId); - _permissions.DeletePermissions(Folder.SiteId, "Folder", FolderId); - _db.Folder.Remove(Folder); + Folder folder = _db.Folder.Find(folderId); + _permissions.DeletePermissions(folder.SiteId, "Folder", folderId); + _db.Folder.Remove(folder); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/Interfaces/IAliasRepository.cs b/Oqtane.Server/Repository/Interfaces/IAliasRepository.cs index 3ab61f13..4f258307 100644 --- a/Oqtane.Server/Repository/Interfaces/IAliasRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IAliasRepository.cs @@ -6,9 +6,9 @@ namespace Oqtane.Repository public interface IAliasRepository { IEnumerable GetAliases(); - Alias AddAlias(Alias Alias); - Alias UpdateAlias(Alias Alias); - Alias GetAlias(int AliasId); - void DeleteAlias(int AliasId); + Alias AddAlias(Alias alias); + Alias UpdateAlias(Alias alias); + Alias GetAlias(int aliasId); + void DeleteAlias(int aliasId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IFileRepository.cs b/Oqtane.Server/Repository/Interfaces/IFileRepository.cs index 3122898b..19715187 100644 --- a/Oqtane.Server/Repository/Interfaces/IFileRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IFileRepository.cs @@ -5,10 +5,10 @@ namespace Oqtane.Repository { public interface IFileRepository { - IEnumerable GetFiles(int FolderId); - File AddFile(File File); - File UpdateFile(File File); - File GetFile(int FileId); - void DeleteFile(int FileId); + IEnumerable GetFiles(int folderId); + File AddFile(File file); + File UpdateFile(File file); + File GetFile(int fileId); + void DeleteFile(int fileId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IFolderRepository.cs b/Oqtane.Server/Repository/Interfaces/IFolderRepository.cs index 86ac797f..65256184 100644 --- a/Oqtane.Server/Repository/Interfaces/IFolderRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IFolderRepository.cs @@ -5,11 +5,11 @@ namespace Oqtane.Repository { public interface IFolderRepository { - IEnumerable GetFolders(int SiteId); - Folder AddFolder(Folder Folder); - Folder UpdateFolder(Folder Folder); - Folder GetFolder(int FolderId); - Folder GetFolder(int SiteId, string Path); - void DeleteFolder(int FolderId); + IEnumerable GetFolders(int siteId); + Folder AddFolder(Folder folder); + Folder UpdateFolder(Folder folder); + Folder GetFolder(int folderId); + Folder GetFolder(int siteId, string path); + void DeleteFolder(int folderId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IJobLogRepository.cs b/Oqtane.Server/Repository/Interfaces/IJobLogRepository.cs index f99de0d2..d5858da5 100644 --- a/Oqtane.Server/Repository/Interfaces/IJobLogRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IJobLogRepository.cs @@ -6,9 +6,9 @@ namespace Oqtane.Repository public interface IJobLogRepository { IEnumerable GetJobLogs(); - JobLog AddJobLog(JobLog JobLog); - JobLog UpdateJobLog(JobLog JobLog); - JobLog GetJobLog(int JobLogId); - void DeleteJobLog(int JobLogId); + JobLog AddJobLog(JobLog jobLog); + JobLog UpdateJobLog(JobLog jobLog); + JobLog GetJobLog(int jobLogId); + void DeleteJobLog(int jobLogId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IJobRepository.cs b/Oqtane.Server/Repository/Interfaces/IJobRepository.cs index 8683009f..12be85c1 100644 --- a/Oqtane.Server/Repository/Interfaces/IJobRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IJobRepository.cs @@ -6,9 +6,9 @@ namespace Oqtane.Repository public interface IJobRepository { IEnumerable GetJobs(); - Job AddJob(Job Job); - Job UpdateJob(Job Job); - Job GetJob(int JobId); - void DeleteJob(int JobId); + Job AddJob(Job job); + Job UpdateJob(Job job); + Job GetJob(int jobId); + void DeleteJob(int jobId); } } diff --git a/Oqtane.Server/Repository/Interfaces/ILogRepository.cs b/Oqtane.Server/Repository/Interfaces/ILogRepository.cs index e4a82e09..27752a03 100644 --- a/Oqtane.Server/Repository/Interfaces/ILogRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/ILogRepository.cs @@ -1,12 +1,12 @@ -using Oqtane.Models; -using System.Collections.Generic; +using System.Collections.Generic; +using Oqtane.Models; namespace Oqtane.Repository { public interface ILogRepository { - IEnumerable GetLogs(int SiteId, string Level, string Function, int Rows); - Log GetLog(int LogId); - void AddLog(Log Log); + IEnumerable GetLogs(int siteId, string level, string function, int rows); + Log GetLog(int logId); + void AddLog(Log log); } } diff --git a/Oqtane.Server/Repository/Interfaces/IModuleDefinitionRepository.cs b/Oqtane.Server/Repository/Interfaces/IModuleDefinitionRepository.cs index c629d76f..32c59549 100644 --- a/Oqtane.Server/Repository/Interfaces/IModuleDefinitionRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IModuleDefinitionRepository.cs @@ -5,9 +5,9 @@ namespace Oqtane.Repository { public interface IModuleDefinitionRepository { - IEnumerable GetModuleDefinitions(int SideId); - ModuleDefinition GetModuleDefinition(int ModuleDefinitionId, int SideId); - void UpdateModuleDefinition(ModuleDefinition ModuleDefinition); - void DeleteModuleDefinition(int ModuleDefinitionId, int SiteId); + IEnumerable GetModuleDefinitions(int sideId); + ModuleDefinition GetModuleDefinition(int moduleDefinitionId, int sideId); + void UpdateModuleDefinition(ModuleDefinition moduleDefinition); + void DeleteModuleDefinition(int moduleDefinitionId, int siteId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IModuleRepository.cs b/Oqtane.Server/Repository/Interfaces/IModuleRepository.cs index 5dd23858..2ef4185d 100644 --- a/Oqtane.Server/Repository/Interfaces/IModuleRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IModuleRepository.cs @@ -5,12 +5,12 @@ namespace Oqtane.Repository { public interface IModuleRepository { - IEnumerable GetModules(int SiteId); - Module AddModule(Module Module); - Module UpdateModule(Module Module); - Module GetModule(int ModuleId); - void DeleteModule(int ModuleId); - string ExportModule(int ModuleId); - bool ImportModule(int ModuleId, string Content); + IEnumerable GetModules(int siteId); + Module AddModule(Module module); + Module UpdateModule(Module module); + Module GetModule(int moduleId); + void DeleteModule(int moduleId); + string ExportModule(int moduleId); + bool ImportModule(int moduleId, string content); } } diff --git a/Oqtane.Server/Repository/Interfaces/INotificationRepository.cs b/Oqtane.Server/Repository/Interfaces/INotificationRepository.cs index 9b1a6a56..ef53bc3a 100644 --- a/Oqtane.Server/Repository/Interfaces/INotificationRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/INotificationRepository.cs @@ -5,10 +5,10 @@ namespace Oqtane.Repository { public interface INotificationRepository { - IEnumerable GetNotifications(int SiteId, int FromUserId, int ToUserId); - Notification AddNotification(Notification Notification); - Notification UpdateNotification(Notification Notification); - Notification GetNotification(int NotificationId); - void DeleteNotification(int NotificationId); + IEnumerable GetNotifications(int siteId, int fromUserId, int toUserId); + Notification AddNotification(Notification notification); + Notification UpdateNotification(Notification notification); + Notification GetNotification(int notificationId); + void DeleteNotification(int notificationId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IPageModuleRepository.cs b/Oqtane.Server/Repository/Interfaces/IPageModuleRepository.cs index 8e275bcb..181fb629 100644 --- a/Oqtane.Server/Repository/Interfaces/IPageModuleRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IPageModuleRepository.cs @@ -5,12 +5,12 @@ namespace Oqtane.Repository { public interface IPageModuleRepository { - IEnumerable GetPageModules(int SiteId); - IEnumerable GetPageModules(int PageId, string Pane); - PageModule AddPageModule(PageModule PageModule); - PageModule UpdatePageModule(PageModule PageModule); - PageModule GetPageModule(int PageModuleId); - PageModule GetPageModule(int PageId, int ModuleId); - void DeletePageModule(int PageModuleId); + IEnumerable GetPageModules(int siteId); + IEnumerable GetPageModules(int pageId, string pane); + PageModule AddPageModule(PageModule pageModule); + PageModule UpdatePageModule(PageModule pageModule); + PageModule GetPageModule(int pageModuleId); + PageModule GetPageModule(int pageId, int moduleId); + void DeletePageModule(int pageModuleId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IPageRepository.cs b/Oqtane.Server/Repository/Interfaces/IPageRepository.cs index 9f98c5ac..6db92dba 100644 --- a/Oqtane.Server/Repository/Interfaces/IPageRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IPageRepository.cs @@ -5,12 +5,12 @@ namespace Oqtane.Repository { public interface IPageRepository { - IEnumerable GetPages(int SiteId); - Page AddPage(Page Page); - Page UpdatePage(Page Page); - Page GetPage(int PageId); - Page GetPage(int PageId, int UserId); - Page GetPage(string Path, int SiteId); - void DeletePage(int PageId); + IEnumerable GetPages(int siteId); + Page AddPage(Page page); + Page UpdatePage(Page page); + Page GetPage(int pageId); + Page GetPage(int pageId, int userId); + Page GetPage(string path, int siteId); + void DeletePage(int pageId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IPermissionRepository.cs b/Oqtane.Server/Repository/Interfaces/IPermissionRepository.cs index 50d53cb0..2fe96254 100644 --- a/Oqtane.Server/Repository/Interfaces/IPermissionRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IPermissionRepository.cs @@ -5,16 +5,16 @@ namespace Oqtane.Repository { public interface IPermissionRepository { - IEnumerable GetPermissions(int SiteId, string EntityName); - IEnumerable GetPermissions(string EntityName, int EntityId); - IEnumerable GetPermissions(string EntityName, int EntityId, string PermissionName); - Permission AddPermission(Permission Permission); - Permission UpdatePermission(Permission Permission); - void UpdatePermissions(int SiteId, string EntityName, int EntityId, string Permissions); - Permission GetPermission(int PermissionId); - void DeletePermission(int PermissionId); - void DeletePermissions(int SiteId, string EntityName, int EntityId); - string EncodePermissions(int EntityId, IEnumerable Permissions); - IEnumerable DecodePermissions(string Permissions, int SiteId, string EntityName, int EntityId); + IEnumerable GetPermissions(int siteId, string entityName); + IEnumerable GetPermissions(string entityName, int entityId); + IEnumerable GetPermissions(string entityName, int entityId, string permissionName); + Permission AddPermission(Permission permission); + Permission UpdatePermission(Permission permission); + void UpdatePermissions(int siteId, string entityName, int entityId, string permissionStrings); + Permission GetPermission(int permissionId); + void DeletePermission(int permissionId); + void DeletePermissions(int siteId, string entityName, int entityId); + string EncodePermissions(int entityId, IEnumerable permissionList); + IEnumerable DecodePermissions(string permissions, int siteId, string entityName, int entityId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IProfileRepository.cs b/Oqtane.Server/Repository/Interfaces/IProfileRepository.cs index e5300b59..c9b4f34b 100644 --- a/Oqtane.Server/Repository/Interfaces/IProfileRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IProfileRepository.cs @@ -5,10 +5,10 @@ namespace Oqtane.Repository { public interface IProfileRepository { - IEnumerable GetProfiles(int SiteId); - Profile AddProfile(Profile Profile); - Profile UpdateProfile(Profile Profile); - Profile GetProfile(int ProfileId); - void DeleteProfile(int ProfileId); + IEnumerable GetProfiles(int siteId); + Profile AddProfile(Profile profile); + Profile UpdateProfile(Profile profile); + Profile GetProfile(int profileId); + void DeleteProfile(int profileId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IRoleRepository.cs b/Oqtane.Server/Repository/Interfaces/IRoleRepository.cs index 40541100..35f9315f 100644 --- a/Oqtane.Server/Repository/Interfaces/IRoleRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IRoleRepository.cs @@ -5,11 +5,11 @@ namespace Oqtane.Repository { public interface IRoleRepository { - IEnumerable GetRoles(int SiteId); - IEnumerable GetRoles(int SiteId, bool IncludeGlobalRoles); - Role AddRole(Role Role); - Role UpdateRole(Role Role); - Role GetRole(int RoleId); - void DeleteRole(int RoleId); + IEnumerable GetRoles(int siteId); + IEnumerable GetRoles(int siteId, bool includeGlobalRoles); + Role AddRole(Role role); + Role UpdateRole(Role role); + Role GetRole(int roleId); + void DeleteRole(int roleId); } } diff --git a/Oqtane.Server/Repository/Interfaces/ISettingRepository.cs b/Oqtane.Server/Repository/Interfaces/ISettingRepository.cs index 0ffad860..976519fb 100644 --- a/Oqtane.Server/Repository/Interfaces/ISettingRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/ISettingRepository.cs @@ -5,10 +5,10 @@ namespace Oqtane.Repository { public interface ISettingRepository { - IEnumerable GetSettings(string EntityName, int EntityId); - Setting AddSetting(Setting Setting); - Setting UpdateSetting(Setting Setting); - Setting GetSetting(int SettingId); - void DeleteSetting(int SettingId); + IEnumerable GetSettings(string entityName, int entityId); + Setting AddSetting(Setting setting); + Setting UpdateSetting(Setting setting); + Setting GetSetting(int settingId); + void DeleteSetting(int settingId); } } diff --git a/Oqtane.Server/Repository/Interfaces/ISiteRepository.cs b/Oqtane.Server/Repository/Interfaces/ISiteRepository.cs index 65cf9aff..5e05dccf 100644 --- a/Oqtane.Server/Repository/Interfaces/ISiteRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/ISiteRepository.cs @@ -6,9 +6,9 @@ namespace Oqtane.Repository public interface ISiteRepository { IEnumerable GetSites(); - Site AddSite(Site Site); - Site UpdateSite(Site Site); - Site GetSite(int SiteId); - void DeleteSite(int SiteId); + Site AddSite(Site site); + Site UpdateSite(Site site); + Site GetSite(int siteId); + void DeleteSite(int siteId); } } diff --git a/Oqtane.Server/Repository/Interfaces/ITenantRepository.cs b/Oqtane.Server/Repository/Interfaces/ITenantRepository.cs index 17a8b1d0..5993eb63 100644 --- a/Oqtane.Server/Repository/Interfaces/ITenantRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/ITenantRepository.cs @@ -1,14 +1,14 @@ -using Oqtane.Models; -using System.Collections.Generic; +using System.Collections.Generic; +using Oqtane.Models; namespace Oqtane.Repository { public interface ITenantRepository { IEnumerable GetTenants(); - Tenant AddTenant(Tenant Tenant); - Tenant UpdateTenant(Tenant Tenant); - Tenant GetTenant(int TenantId); - void DeleteTenant(int TenantId); + Tenant AddTenant(Tenant tenant); + Tenant UpdateTenant(Tenant tenant); + Tenant GetTenant(int tenantId); + void DeleteTenant(int tenantId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IUserRepository.cs b/Oqtane.Server/Repository/Interfaces/IUserRepository.cs index 63757b49..be646e56 100644 --- a/Oqtane.Server/Repository/Interfaces/IUserRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IUserRepository.cs @@ -6,10 +6,10 @@ namespace Oqtane.Repository public interface IUserRepository { IEnumerable GetUsers(); - User AddUser(User User); - User UpdateUser(User User); - User GetUser(int UserId); - User GetUser(string Username); - void DeleteUser(int UserId); + User AddUser(User user); + User UpdateUser(User user); + User GetUser(int userId); + User GetUser(string username); + void DeleteUser(int userId); } } diff --git a/Oqtane.Server/Repository/Interfaces/IUserRoleRepository.cs b/Oqtane.Server/Repository/Interfaces/IUserRoleRepository.cs index 14cb81a4..c46a0e50 100644 --- a/Oqtane.Server/Repository/Interfaces/IUserRoleRepository.cs +++ b/Oqtane.Server/Repository/Interfaces/IUserRoleRepository.cs @@ -5,11 +5,11 @@ namespace Oqtane.Repository { public interface IUserRoleRepository { - IEnumerable GetUserRoles(int SiteId); - IEnumerable GetUserRoles(int UserId, int SiteId); - UserRole AddUserRole(UserRole UserRole); - UserRole UpdateUserRole(UserRole UserRole); - UserRole GetUserRole(int UserRoleId); - void DeleteUserRole(int UserRoleId); + IEnumerable GetUserRoles(int siteId); + IEnumerable GetUserRoles(int userId, int siteId); + UserRole AddUserRole(UserRole userRole); + UserRole UpdateUserRole(UserRole userRole); + UserRole GetUserRole(int userRoleId); + void DeleteUserRole(int userRoleId); } } diff --git a/Oqtane.Server/Repository/JobLogRepository.cs b/Oqtane.Server/Repository/JobLogRepository.cs index cdfca1c0..440a483d 100644 --- a/Oqtane.Server/Repository/JobLogRepository.cs +++ b/Oqtane.Server/Repository/JobLogRepository.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using Microsoft.EntityFrameworkCore; +using Oqtane.Models; namespace Oqtane.Repository { @@ -21,30 +21,30 @@ namespace Oqtane.Repository .ToList(); } - public JobLog AddJobLog(JobLog JobLog) + public JobLog AddJobLog(JobLog jobLog) { - _db.JobLog.Add(JobLog); + _db.JobLog.Add(jobLog); _db.SaveChanges(); - return JobLog; + return jobLog; } - public JobLog UpdateJobLog(JobLog JobLog) + public JobLog UpdateJobLog(JobLog jobLog) { - _db.Entry(JobLog).State = EntityState.Modified; + _db.Entry(jobLog).State = EntityState.Modified; _db.SaveChanges(); - return JobLog; + return jobLog; } - public JobLog GetJobLog(int JobLogId) + public JobLog GetJobLog(int jobLogId) { return _db.JobLog.Include(item => item.Job) // eager load job - .SingleOrDefault(item => item.JobLogId == JobLogId); + .SingleOrDefault(item => item.JobLogId == jobLogId); } - public void DeleteJobLog(int JobLogId) + public void DeleteJobLog(int jobLogId) { - JobLog Joblog = _db.JobLog.Find(JobLogId); - _db.JobLog.Remove(Joblog); + JobLog joblog = _db.JobLog.Find(jobLogId); + _db.JobLog.Remove(joblog); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/JobRepository.cs b/Oqtane.Server/Repository/JobRepository.cs index 2d146142..2ea8b7d1 100644 --- a/Oqtane.Server/Repository/JobRepository.cs +++ b/Oqtane.Server/Repository/JobRepository.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using Microsoft.EntityFrameworkCore; -using System; using Microsoft.Extensions.Caching.Memory; +using Oqtane.Models; namespace Oqtane.Repository { @@ -27,29 +27,29 @@ namespace Oqtane.Repository }); } - public Job AddJob(Job Job) + public Job AddJob(Job job) { - _db.Job.Add(Job); + _db.Job.Add(job); _db.SaveChanges(); - return Job; + return job; } - public Job UpdateJob(Job Job) + public Job UpdateJob(Job job) { - _db.Entry(Job).State = EntityState.Modified; + _db.Entry(job).State = EntityState.Modified; _db.SaveChanges(); - return Job; + return job; } - public Job GetJob(int JobId) + public Job GetJob(int jobId) { - return _db.Job.Find(JobId); + return _db.Job.Find(jobId); } - public void DeleteJob(int JobId) + public void DeleteJob(int jobId) { - Job Job = _db.Job.Find(JobId); - _db.Job.Remove(Job); + Job job = _db.Job.Find(jobId); + _db.Job.Remove(job); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/LogRepository.cs b/Oqtane.Server/Repository/LogRepository.cs index b01bc069..1bcbc2be 100644 --- a/Oqtane.Server/Repository/LogRepository.cs +++ b/Oqtane.Server/Repository/LogRepository.cs @@ -1,5 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Oqtane.Models; @@ -14,44 +13,38 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetLogs(int SiteId, string Level, string Function, int Rows) + public IEnumerable GetLogs(int siteId, string level, string function, int rows) { - if (Level == null) + if (level == null) { - if (Function == null) + if (function == null) { - return _db.Log.Where(item => item.SiteId == SiteId). - OrderByDescending(item => item.LogDate).Take(Rows); - } - else - { - return _db.Log.Where(item => item.SiteId == SiteId && item.Function == Function). - OrderByDescending(item => item.LogDate).Take(Rows); + return _db.Log.Where(item => item.SiteId == siteId). + OrderByDescending(item => item.LogDate).Take(rows); } + + return _db.Log.Where(item => item.SiteId == siteId && item.Function == function). + OrderByDescending(item => item.LogDate).Take(rows); } - else + + if (function == null) { - if (Function == null) - { - return _db.Log.Where(item => item.SiteId == SiteId && item.Level == Level) - .OrderByDescending(item => item.LogDate).Take(Rows); - } - else - { - return _db.Log.Where(item => item.SiteId == SiteId && item.Level == Level && item.Function == Function) - .OrderByDescending(item => item.LogDate).Take(Rows); - } + return _db.Log.Where(item => item.SiteId == siteId && item.Level == level) + .OrderByDescending(item => item.LogDate).Take(rows); } + + return _db.Log.Where(item => item.SiteId == siteId && item.Level == level && item.Function == function) + .OrderByDescending(item => item.LogDate).Take(rows); } - public Log GetLog(int LogId) + public Log GetLog(int logId) { - return _db.Log.Find(LogId); + return _db.Log.Find(logId); } - public void AddLog(Log Log) + public void AddLog(Log log) { - _db.Log.Add(Log); + _db.Log.Add(log); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/ModuleDefinitionRepository.cs b/Oqtane.Server/Repository/ModuleDefinitionRepository.cs index c13b86d2..509a7bcf 100644 --- a/Oqtane.Server/Repository/ModuleDefinitionRepository.cs +++ b/Oqtane.Server/Repository/ModuleDefinitionRepository.cs @@ -1,11 +1,10 @@ -using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using System.Reflection; -using System; -using Oqtane.Modules; using Microsoft.Extensions.Caching.Memory; +using Oqtane.Models; +using Oqtane.Modules; using Oqtane.Shared; namespace Oqtane.Repository @@ -23,51 +22,51 @@ namespace Oqtane.Repository _permissions = permissions; } - public IEnumerable GetModuleDefinitions(int SiteId) + public IEnumerable GetModuleDefinitions(int siteId) { - return LoadModuleDefinitions(SiteId); + return LoadModuleDefinitions(siteId); } - public ModuleDefinition GetModuleDefinition(int ModuleDefinitionId, int SiteId) + public ModuleDefinition GetModuleDefinition(int moduleDefinitionId, int siteId) { - List moduledefinitions = LoadModuleDefinitions(SiteId); - return moduledefinitions.Find(item => item.ModuleDefinitionId == ModuleDefinitionId); + List moduledefinitions = LoadModuleDefinitions(siteId); + return moduledefinitions.Find(item => item.ModuleDefinitionId == moduleDefinitionId); } - public void UpdateModuleDefinition(ModuleDefinition ModuleDefinition) + public void UpdateModuleDefinition(ModuleDefinition moduleDefinition) { - _permissions.UpdatePermissions(ModuleDefinition.SiteId, "ModuleDefinition", ModuleDefinition.ModuleDefinitionId, ModuleDefinition.Permissions); + _permissions.UpdatePermissions(moduleDefinition.SiteId, "ModuleDefinition", moduleDefinition.ModuleDefinitionId, moduleDefinition.Permissions); _cache.Remove("moduledefinitions"); } - public void DeleteModuleDefinition(int ModuleDefinitionId, int SiteId) + public void DeleteModuleDefinition(int moduleDefinitionId, int siteId) { - ModuleDefinition ModuleDefinition = _db.ModuleDefinition.Find(ModuleDefinitionId); - _permissions.DeletePermissions(SiteId, "ModuleDefinition", ModuleDefinitionId); - _db.ModuleDefinition.Remove(ModuleDefinition); + ModuleDefinition moduleDefinition = _db.ModuleDefinition.Find(moduleDefinitionId); + _permissions.DeletePermissions(siteId, "ModuleDefinition", moduleDefinitionId); + _db.ModuleDefinition.Remove(moduleDefinition); _db.SaveChanges(); _cache.Remove("moduledefinitions"); } - public List LoadModuleDefinitions(int SiteId) + public List LoadModuleDefinitions(int siteId) { - List ModuleDefinitions; + List moduleDefinitions; // get run-time module definitions - ModuleDefinitions = _cache.GetOrCreate("moduledefinitions", entry => + moduleDefinitions = _cache.GetOrCreate("moduledefinitions", entry => { entry.SlidingExpiration = TimeSpan.FromMinutes(30); return LoadModuleDefinitionsFromAssemblies(); }); // get module defintion permissions for site - List permissions = _permissions.GetPermissions(SiteId, "ModuleDefinition").ToList(); + List permissions = _permissions.GetPermissions(siteId, "ModuleDefinition").ToList(); // get module definitions in database List moduledefs = _db.ModuleDefinition.ToList(); // sync run-time module definitions with database - foreach (ModuleDefinition moduledefinition in ModuleDefinitions) + foreach (ModuleDefinition moduledefinition in moduleDefinitions) { ModuleDefinition moduledef = moduledefs.Where(item => item.ModuleDefinitionName == moduledefinition.ModuleDefinitionName).FirstOrDefault(); if (moduledef == null) @@ -76,14 +75,14 @@ namespace Oqtane.Repository moduledef = new ModuleDefinition { ModuleDefinitionName = moduledefinition.ModuleDefinitionName }; _db.ModuleDefinition.Add(moduledef); _db.SaveChanges(); - _permissions.UpdatePermissions(SiteId, "ModuleDefinition", moduledef.ModuleDefinitionId, moduledefinition.Permissions); + _permissions.UpdatePermissions(siteId, "ModuleDefinition", moduledef.ModuleDefinitionId, moduledefinition.Permissions); } else { // existing module definition if (permissions.Count == 0) { - _permissions.UpdatePermissions(SiteId, "ModuleDefinition", moduledef.ModuleDefinitionId, moduledefinition.Permissions); + _permissions.UpdatePermissions(siteId, "ModuleDefinition", moduledef.ModuleDefinitionId, moduledefinition.Permissions); } else { @@ -93,7 +92,7 @@ namespace Oqtane.Repository moduledefs.Remove(moduledef); } moduledefinition.ModuleDefinitionId = moduledef.ModuleDefinitionId; - moduledefinition.SiteId = SiteId; + moduledefinition.SiteId = siteId; moduledefinition.CreatedBy = moduledef.CreatedBy; moduledefinition.CreatedOn = moduledef.CreatedOn; moduledefinition.ModifiedBy = moduledef.ModifiedBy; @@ -103,24 +102,24 @@ namespace Oqtane.Repository // any remaining module definitions are orphans foreach (ModuleDefinition moduledefinition in moduledefs) { - _permissions.DeletePermissions(SiteId, "ModuleDefinition", moduledefinition.ModuleDefinitionId); + _permissions.DeletePermissions(siteId, "ModuleDefinition", moduledefinition.ModuleDefinitionId); _db.ModuleDefinition.Remove(moduledefinition); // delete } - return ModuleDefinitions; + return moduleDefinitions; } private List LoadModuleDefinitionsFromAssemblies() { - List ModuleDefinitions = new List(); + List moduleDefinitions = new List(); // iterate through Oqtane module assemblies Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(item => item.FullName.StartsWith("Oqtane.") || item.FullName.Contains(".Module.")).ToArray(); foreach (Assembly assembly in assemblies) { - ModuleDefinitions = LoadModuleDefinitionsFromAssembly(ModuleDefinitions, assembly); + moduleDefinitions = LoadModuleDefinitionsFromAssembly(moduleDefinitions, assembly); } - return ModuleDefinitions; + return moduleDefinitions; } private List LoadModuleDefinitionsFromAssembly(List moduledefinitions, Assembly assembly) @@ -134,25 +133,25 @@ namespace Oqtane.Repository string[] typename = modulecontroltype.AssemblyQualifiedName.Split(',').Select(item => item.Trim()).ToList().ToArray(); string[] segments = typename[0].Split('.'); Array.Resize(ref segments, segments.Length - 1); - string ModuleType = string.Join(".", segments); - string QualifiedModuleType = ModuleType + ", " + typename[1]; + string moduleType = string.Join(".", segments); + string qualifiedModuleType = moduleType + ", " + typename[1]; - int index = moduledefinitions.FindIndex(item => item.ModuleDefinitionName == QualifiedModuleType); + int index = moduledefinitions.FindIndex(item => item.ModuleDefinitionName == qualifiedModuleType); if (index == -1) { - /// determine if this module implements IModule - Type moduletype = assembly.GetTypes() - .Where(item => item.Namespace != null) - .Where(item => item.Namespace.StartsWith(ModuleType)) - .Where(item => item.GetInterfaces().Contains(typeof(IModule))) - .FirstOrDefault(); + // determine if this module implements IModule + Type moduletype = assembly + .GetTypes() + .Where(item => item.Namespace != null) + .Where(item => item.Namespace.StartsWith(moduleType)) + .FirstOrDefault(item => item.GetInterfaces().Contains(typeof(IModule))); if (moduletype != null) { var moduleobject = Activator.CreateInstance(moduletype); Dictionary properties = (Dictionary)moduletype.GetProperty("Properties").GetValue(moduleobject); moduledefinition = new ModuleDefinition { - ModuleDefinitionName = QualifiedModuleType, + ModuleDefinitionName = qualifiedModuleType, Name = GetProperty(properties, "Name"), Description = GetProperty(properties, "Description"), Categories = GetProperty(properties, "Categories"), @@ -164,7 +163,7 @@ namespace Oqtane.Repository Dependencies = GetProperty(properties, "Dependencies"), PermissionNames = GetProperty(properties, "PermissionNames"), ServerAssemblyName = GetProperty(properties, "ServerAssemblyName"), - ControlTypeTemplate = ModuleType + "." + Constants.ActionToken + ", " + typename[1], + ControlTypeTemplate = moduleType + "." + Constants.ActionToken + ", " + typename[1], ControlTypeRoutes = "", AssemblyName = assembly.FullName.Split(",")[0], Permissions = "" @@ -174,10 +173,10 @@ namespace Oqtane.Repository { moduledefinition = new ModuleDefinition { - ModuleDefinitionName = QualifiedModuleType, - Name = ModuleType.Substring(ModuleType.LastIndexOf(".") + 1), - Description = ModuleType.Substring(ModuleType.LastIndexOf(".") + 1), - Categories = ((QualifiedModuleType.StartsWith("Oqtane.Modules.Admin.")) ? "Admin" : ""), + ModuleDefinitionName = qualifiedModuleType, + Name = moduleType.Substring(moduleType.LastIndexOf(".") + 1), + Description = moduleType.Substring(moduleType.LastIndexOf(".") + 1), + Categories = ((qualifiedModuleType.StartsWith("Oqtane.Modules.Admin.")) ? "Admin" : ""), Version = new Version(1, 0, 0).ToString(), Owner = "", Url = "", @@ -186,7 +185,7 @@ namespace Oqtane.Repository Dependencies = "", PermissionNames = "", ServerAssemblyName = "", - ControlTypeTemplate = ModuleType + "." + Constants.ActionToken + ", " + typename[1], + ControlTypeTemplate = moduleType + "." + Constants.ActionToken + ", " + typename[1], ControlTypeRoutes = "", AssemblyName = assembly.FullName.Split(",")[0], Permissions = "" @@ -202,7 +201,7 @@ namespace Oqtane.Repository moduledefinition.Permissions = "[{\"PermissionName\":\"Utilize\",\"Permissions\":\"" + Constants.AdminRole + ";" + Constants.RegisteredRole + "\"}]"; } moduledefinitions.Add(moduledefinition); - index = moduledefinitions.FindIndex(item => item.ModuleDefinitionName == QualifiedModuleType); + index = moduledefinitions.FindIndex(item => item.ModuleDefinitionName == qualifiedModuleType); } moduledefinition = moduledefinitions[index]; // actions @@ -222,14 +221,14 @@ namespace Oqtane.Repository return moduledefinitions; } - private string GetProperty(Dictionary Properties, string Key) + private string GetProperty(Dictionary properties, string key) { - string Value = ""; - if (Properties.ContainsKey(Key)) + string value = ""; + if (properties.ContainsKey(key)) { - Value = Properties[Key]; + value = properties[key]; } - return Value; + return value; } } } diff --git a/Oqtane.Server/Repository/ModuleRepository.cs b/Oqtane.Server/Repository/ModuleRepository.cs index 7abd0c34..76644286 100644 --- a/Oqtane.Server/Repository/ModuleRepository.cs +++ b/Oqtane.Server/Repository/ModuleRepository.cs @@ -1,12 +1,13 @@ -using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using System.Reflection; -using System; -using Oqtane.Modules; -using Microsoft.Extensions.DependencyInjection; using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Oqtane.Models; +using Oqtane.Modules; +using Module = Oqtane.Models.Module; namespace Oqtane.Repository { @@ -25,30 +26,30 @@ namespace Oqtane.Repository _serviceProvider = serviceProvider; } - public IEnumerable GetModules(int SiteId) + public IEnumerable GetModules(int siteId) { - return _db.Module.Where(item => item.SiteId == SiteId).ToList(); + return _db.Module.Where(item => item.SiteId == siteId).ToList(); } - public Models.Module AddModule(Models.Module Module) + public Module AddModule(Module module) { - _db.Module.Add(Module); + _db.Module.Add(module); _db.SaveChanges(); - _permissions.UpdatePermissions(Module.SiteId, "Module", Module.ModuleId, Module.Permissions); - return Module; + _permissions.UpdatePermissions(module.SiteId, "Module", module.ModuleId, module.Permissions); + return module; } - public Models.Module UpdateModule(Models.Module Module) + public Module UpdateModule(Module module) { - _db.Entry(Module).State = EntityState.Modified; + _db.Entry(module).State = EntityState.Modified; _db.SaveChanges(); - _permissions.UpdatePermissions(Module.SiteId, "Module", Module.ModuleId, Module.Permissions); - return Module; + _permissions.UpdatePermissions(module.SiteId, "Module", module.ModuleId, module.Permissions); + return module; } - public Models.Module GetModule(int ModuleId) + public Module GetModule(int moduleId) { - Models.Module module = _db.Module.Find(ModuleId); + Module module = _db.Module.Find(moduleId); if (module != null) { List permissions = _permissions.GetPermissions("Module", module.ModuleId).ToList(); @@ -57,20 +58,20 @@ namespace Oqtane.Repository return module; } - public void DeleteModule(int ModuleId) + public void DeleteModule(int moduleId) { - Models.Module Module = _db.Module.Find(ModuleId); - _permissions.DeletePermissions(Module.SiteId, "Module", ModuleId); - _db.Module.Remove(Module); + Module module = _db.Module.Find(moduleId); + _permissions.DeletePermissions(module.SiteId, "Module", moduleId); + _db.Module.Remove(module); _db.SaveChanges(); } - public string ExportModule(int ModuleId) + public string ExportModule(int moduleId) { string content = ""; try { - Models.Module module = GetModule(ModuleId); + Module module = GetModule(moduleId); if (module != null) { List moduledefinitions = _moduleDefinitions.GetModuleDefinitions(module.SiteId).ToList(); @@ -110,19 +111,19 @@ namespace Oqtane.Repository return content; } - public bool ImportModule(int ModuleId, string Content) + public bool ImportModule(int moduleId, string content) { bool success = false; try { - Models.Module module = GetModule(ModuleId); + Module module = GetModule(moduleId); if (module != null) { List moduledefinitions = _moduleDefinitions.GetModuleDefinitions(module.SiteId).ToList(); ModuleDefinition moduledefinition = moduledefinitions.Where(item => item.ModuleDefinitionName == module.ModuleDefinitionName).FirstOrDefault(); if (moduledefinition != null) { - ModuleContent modulecontent = JsonSerializer.Deserialize(Content); + ModuleContent modulecontent = JsonSerializer.Deserialize(content); if (modulecontent.ModuleDefinitionName == moduledefinition.ModuleDefinitionName) { if (moduledefinition.ServerAssemblyName != "") diff --git a/Oqtane.Server/Repository/NotificationRepository.cs b/Oqtane.Server/Repository/NotificationRepository.cs index dbc00564..8f34ff50 100644 --- a/Oqtane.Server/Repository/NotificationRepository.cs +++ b/Oqtane.Server/Repository/NotificationRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -14,52 +14,50 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetNotifications(int SiteId, int FromUserId, int ToUserId) + public IEnumerable GetNotifications(int siteId, int fromUserId, int toUserId) { - if (ToUserId == -1 && FromUserId == -1) + if (toUserId == -1 && fromUserId == -1) { return _db.Notification - .Where(item => item.SiteId == SiteId) + .Where(item => item.SiteId == siteId) .Where(item => item.IsDelivered == false) .Include(item => item.FromUser) .Include(item => item.ToUser) .ToList(); } - else - { - return _db.Notification - .Where(item => item.SiteId == SiteId) - .Where(item => item.ToUserId == ToUserId || ToUserId == -1) - .Where(item => item.FromUserId == FromUserId || FromUserId == -1) - .Include(item => item.FromUser) - .Include(item => item.ToUser) - .ToList(); - } + + return _db.Notification + .Where(item => item.SiteId == siteId) + .Where(item => item.ToUserId == toUserId || toUserId == -1) + .Where(item => item.FromUserId == fromUserId || fromUserId == -1) + .Include(item => item.FromUser) + .Include(item => item.ToUser) + .ToList(); } - public Notification AddNotification(Notification Notification) + public Notification AddNotification(Notification notification) { - _db.Notification.Add(Notification); + _db.Notification.Add(notification); _db.SaveChanges(); - return Notification; + return notification; } - public Notification UpdateNotification(Notification Notification) + public Notification UpdateNotification(Notification notification) { - _db.Entry(Notification).State = EntityState.Modified; + _db.Entry(notification).State = EntityState.Modified; _db.SaveChanges(); - return Notification; + return notification; } - public Notification GetNotification(int NotificationId) + public Notification GetNotification(int notificationId) { - return _db.Notification.Find(NotificationId); + return _db.Notification.Find(notificationId); } - public void DeleteNotification(int NotificationId) + public void DeleteNotification(int notificationId) { - Notification Notification = _db.Notification.Find(NotificationId); - _db.Notification.Remove(Notification); + Notification notification = _db.Notification.Find(notificationId); + _db.Notification.Remove(notification); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/PageModuleRepository.cs b/Oqtane.Server/Repository/PageModuleRepository.cs index 8493c7f1..70f7c201 100644 --- a/Oqtane.Server/Repository/PageModuleRepository.cs +++ b/Oqtane.Server/Repository/PageModuleRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -16,11 +16,11 @@ namespace Oqtane.Repository _permissions = permissions; } - public IEnumerable GetPageModules(int SiteId) + public IEnumerable GetPageModules(int siteId) { IEnumerable pagemodules = _db.PageModule .Include(item => item.Module) // eager load modules - .Where(item => item.Module.SiteId == SiteId); + .Where(item => item.Module.SiteId == siteId); if (pagemodules != null && pagemodules.Any()) { IEnumerable permissions = _permissions.GetPermissions(pagemodules.FirstOrDefault().Module.SiteId, "Module").ToList(); @@ -32,14 +32,14 @@ namespace Oqtane.Repository return pagemodules; } - public IEnumerable GetPageModules(int PageId, string Pane) + public IEnumerable GetPageModules(int pageId, string pane) { IEnumerable pagemodules = _db.PageModule .Include(item => item.Module) // eager load modules - .Where(item => item.PageId == PageId); - if (Pane != "" && pagemodules != null && pagemodules.Any()) + .Where(item => item.PageId == pageId); + if (pane != "" && pagemodules != null && pagemodules.Any()) { - pagemodules = pagemodules.Where(item => item.Pane == Pane); + pagemodules = pagemodules.Where(item => item.Pane == pane); } if (pagemodules != null && pagemodules.Any()) { @@ -52,24 +52,24 @@ namespace Oqtane.Repository return pagemodules; } - public PageModule AddPageModule(PageModule PageModule) + public PageModule AddPageModule(PageModule pageModule) { - _db.PageModule.Add(PageModule); + _db.PageModule.Add(pageModule); _db.SaveChanges(); - return PageModule; + return pageModule; } - public PageModule UpdatePageModule(PageModule PageModule) + public PageModule UpdatePageModule(PageModule pageModule) { - _db.Entry(PageModule).State = EntityState.Modified; + _db.Entry(pageModule).State = EntityState.Modified; _db.SaveChanges(); - return PageModule; + return pageModule; } - public PageModule GetPageModule(int PageModuleId) + public PageModule GetPageModule(int pageModuleId) { PageModule pagemodule = _db.PageModule.Include(item => item.Module) // eager load modules - .SingleOrDefault(item => item.PageModuleId == PageModuleId); + .SingleOrDefault(item => item.PageModuleId == pageModuleId); if (pagemodule != null) { IEnumerable permissions = _permissions.GetPermissions("Module", pagemodule.ModuleId).ToList(); @@ -78,10 +78,10 @@ namespace Oqtane.Repository return pagemodule; } - public PageModule GetPageModule(int PageId, int ModuleId) + public PageModule GetPageModule(int pageId, int moduleId) { PageModule pagemodule = _db.PageModule.Include(item => item.Module) // eager load modules - .SingleOrDefault(item => item.PageId == PageId && item.ModuleId == ModuleId); + .SingleOrDefault(item => item.PageId == pageId && item.ModuleId == moduleId); if (pagemodule != null) { IEnumerable permissions = _permissions.GetPermissions("Module", pagemodule.ModuleId).ToList(); @@ -90,10 +90,10 @@ namespace Oqtane.Repository return pagemodule; } - public void DeletePageModule(int PageModuleId) + public void DeletePageModule(int pageModuleId) { - PageModule PageModule = _db.PageModule.Find(PageModuleId); - _db.PageModule.Remove(PageModule); + PageModule pageModule = _db.PageModule.Find(pageModuleId); + _db.PageModule.Remove(pageModule); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/PageRepository.cs b/Oqtane.Server/Repository/PageRepository.cs index a016a88c..f5b726f3 100644 --- a/Oqtane.Server/Repository/PageRepository.cs +++ b/Oqtane.Server/Repository/PageRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -18,10 +18,10 @@ namespace Oqtane.Repository _pageModules = pageModules; } - public IEnumerable GetPages(int SiteId) + public IEnumerable GetPages(int siteId) { - IEnumerable permissions = _permissions.GetPermissions(SiteId, "Page").ToList(); - IEnumerable pages = _db.Page.Where(item => item.SiteId == SiteId && item.UserId == null); + IEnumerable permissions = _permissions.GetPermissions(siteId, "Page").ToList(); + IEnumerable pages = _db.Page.Where(item => item.SiteId == siteId && item.UserId == null); foreach(Page page in pages) { page.Permissions = _permissions.EncodePermissions(page.PageId, permissions); @@ -29,25 +29,25 @@ namespace Oqtane.Repository return pages; } - public Page AddPage(Page Page) + public Page AddPage(Page page) { - _db.Page.Add(Page); + _db.Page.Add(page); _db.SaveChanges(); - _permissions.UpdatePermissions(Page.SiteId, "Page", Page.PageId, Page.Permissions); - return Page; + _permissions.UpdatePermissions(page.SiteId, "Page", page.PageId, page.Permissions); + return page; } - public Page UpdatePage(Page Page) + public Page UpdatePage(Page page) { - _db.Entry(Page).State = EntityState.Modified; + _db.Entry(page).State = EntityState.Modified; _db.SaveChanges(); - _permissions.UpdatePermissions(Page.SiteId, "Page", Page.PageId, Page.Permissions); - return Page; + _permissions.UpdatePermissions(page.SiteId, "Page", page.PageId, page.Permissions); + return page; } - public Page GetPage(int PageId) + public Page GetPage(int pageId) { - Page page = _db.Page.Find(PageId); + Page page = _db.Page.Find(pageId); if (page != null) { IEnumerable permissions = _permissions.GetPermissions("Page", page.PageId).ToList(); @@ -56,12 +56,12 @@ namespace Oqtane.Repository return page; } - public Page GetPage(int PageId, int UserId) + public Page GetPage(int pageId, int userId) { - Page page = _db.Page.Find(PageId); + Page page = _db.Page.Find(pageId); if (page != null) { - Page personalized = _db.Page.Where(item => item.SiteId == page.SiteId && item.Path == page.Path && item.UserId == UserId).FirstOrDefault(); + Page personalized = _db.Page.Where(item => item.SiteId == page.SiteId && item.Path == page.Path && item.UserId == userId).FirstOrDefault(); if (personalized != null) { page = personalized; @@ -75,9 +75,9 @@ namespace Oqtane.Repository return page; } - public Page GetPage(string Path, int SiteId) + public Page GetPage(string path, int siteId) { - Page page = _db.Page.Where(item => item.Path == Path && item.SiteId == SiteId).FirstOrDefault(); + Page page = _db.Page.Where(item => item.Path == path && item.SiteId == siteId).FirstOrDefault(); if (page != null) { IEnumerable permissions = _permissions.GetPermissions("Page", page.PageId).ToList(); @@ -86,16 +86,16 @@ namespace Oqtane.Repository return page; } - public void DeletePage(int PageId) + public void DeletePage(int pageId) { - Page Page = _db.Page.Find(PageId); - _permissions.DeletePermissions(Page.SiteId, "Page", PageId); - IEnumerable pageModules = _db.PageModule.Where(item => item.PageId == PageId).ToList(); + Page page = _db.Page.Find(pageId); + _permissions.DeletePermissions(page.SiteId, "Page", pageId); + IEnumerable pageModules = _db.PageModule.Where(item => item.PageId == pageId).ToList(); foreach (var pageModule in pageModules) { _pageModules.DeletePageModule(pageModule.PageModuleId); } - _db.Page.Remove(Page); + _db.Page.Remove(page); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/PermissionRepository.cs b/Oqtane.Server/Repository/PermissionRepository.cs index f9edc3b6..991d222c 100644 --- a/Oqtane.Server/Repository/PermissionRepository.cs +++ b/Oqtane.Server/Repository/PermissionRepository.cs @@ -1,11 +1,10 @@ -using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using System.Text; -using System; using System.Text.Json; -using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; +using Oqtane.Models; namespace Oqtane.Repository { @@ -20,55 +19,55 @@ namespace Oqtane.Repository _roles = roles; } - public IEnumerable GetPermissions(int SiteId, string EntityName) + public IEnumerable GetPermissions(int siteId, string entityName) { - return _db.Permission.Where(item => item.SiteId == SiteId) - .Where(item => item.EntityName == EntityName) + return _db.Permission.Where(item => item.SiteId == siteId) + .Where(item => item.EntityName == entityName) .Include(item => item.Role); // eager load roles } - public IEnumerable GetPermissions(string EntityName, int EntityId) + public IEnumerable GetPermissions(string entityName, int entityId) { - return _db.Permission.Where(item => item.EntityName == EntityName) - .Where(item => item.EntityId == EntityId) + return _db.Permission.Where(item => item.EntityName == entityName) + .Where(item => item.EntityId == entityId) .Include(item => item.Role); // eager load roles } - public IEnumerable GetPermissions(string EntityName, int EntityId, string PermissionName) + public IEnumerable GetPermissions(string entityName, int entityId, string permissionName) { - return _db.Permission.Where(item => item.EntityName == EntityName) - .Where(item => item.EntityId == EntityId) - .Where(item => item.PermissionName == PermissionName) + return _db.Permission.Where(item => item.EntityName == entityName) + .Where(item => item.EntityId == entityId) + .Where(item => item.PermissionName == permissionName) .Include(item => item.Role); // eager load roles } - public Permission AddPermission(Permission Permission) + public Permission AddPermission(Permission permission) { - _db.Permission.Add(Permission); + _db.Permission.Add(permission); _db.SaveChanges(); - return Permission; + return permission; } - public Permission UpdatePermission(Permission Permission) + public Permission UpdatePermission(Permission permission) { - _db.Entry(Permission).State = EntityState.Modified; + _db.Entry(permission).State = EntityState.Modified; _db.SaveChanges(); - return Permission; + return permission; } - public void UpdatePermissions(int SiteId, string EntityName, int EntityId, string Permissions) + public void UpdatePermissions(int siteId, string entityName, int entityId, string permissionStrings) { // get current permissions and delete IEnumerable permissions = _db.Permission - .Where(item => item.EntityName == EntityName) - .Where(item => item.EntityId == EntityId) - .Where(item => item.SiteId == SiteId); + .Where(item => item.EntityName == entityName) + .Where(item => item.EntityId == entityId) + .Where(item => item.SiteId == siteId); foreach (Permission permission in permissions) { _db.Permission.Remove(permission); } // add permissions - permissions = DecodePermissions(Permissions, SiteId, EntityName, EntityId); + permissions = DecodePermissions(permissionStrings, siteId, entityName, entityId); foreach (Permission permission in permissions) { _db.Permission.Add(permission); @@ -76,24 +75,24 @@ namespace Oqtane.Repository _db.SaveChanges(); } - public Permission GetPermission(int PermissionId) + public Permission GetPermission(int permissionId) { - return _db.Permission.Find(PermissionId); + return _db.Permission.Find(permissionId); } - public void DeletePermission(int PermissionId) + public void DeletePermission(int permissionId) { - Permission Permission = _db.Permission.Find(PermissionId); - _db.Permission.Remove(Permission); + Permission permission = _db.Permission.Find(permissionId); + _db.Permission.Remove(permission); _db.SaveChanges(); } - public void DeletePermissions(int SiteId, string EntityName, int EntityId) + public void DeletePermissions(int siteId, string entityName, int entityId) { IEnumerable permissions = _db.Permission - .Where(item => item.EntityName == EntityName) - .Where(item => item.EntityId == EntityId) - .Where(item => item.SiteId == SiteId); + .Where(item => item.EntityName == entityName) + .Where(item => item.EntityId == entityId) + .Where(item => item.SiteId == siteId); foreach (Permission permission in permissions) { _db.Permission.Remove(permission); @@ -102,14 +101,14 @@ namespace Oqtane.Repository } // permissions are stored in the format "{permissionname:!rolename1;![userid1];rolename2;rolename3;[userid2];[userid3]}" where "!" designates Deny permissions - public string EncodePermissions(int EntityId, IEnumerable Permissions) + public string EncodePermissions(int entityId, IEnumerable permissionList) { List permissionstrings = new List(); string permissionname = ""; string permissions = ""; StringBuilder permissionsbuilder = new StringBuilder(); string securityid = ""; - foreach (Permission permission in Permissions.Where(item => item.EntityId == EntityId).OrderBy(item => item.PermissionName)) + foreach (Permission permission in permissionList.Where(item => item.EntityId == entityId).OrderBy(item => item.PermissionName)) { // permission collections are grouped by permissionname if (permissionname != permission.PermissionName) @@ -133,7 +132,7 @@ namespace Oqtane.Repository } else { - securityid = prefix + "[" + permission.UserId.ToString() + "];"; + securityid = prefix + "[" + permission.UserId + "];"; } // insert deny permissions at the beginning and append grant permissions at the end @@ -155,20 +154,20 @@ namespace Oqtane.Repository return JsonSerializer.Serialize(permissionstrings); } - public IEnumerable DecodePermissions(string PermissionStrings, int SiteId, string EntityName, int EntityId) + public IEnumerable DecodePermissions(string permissionStrings, int siteId, string entityName, int entityId) { List permissions = new List(); - List roles = _roles.GetRoles(SiteId, true).ToList(); + List roles = _roles.GetRoles(siteId, true).ToList(); string securityid = ""; - foreach (PermissionString permissionstring in JsonSerializer.Deserialize>(PermissionStrings)) + foreach (PermissionString permissionstring in JsonSerializer.Deserialize>(permissionStrings)) { foreach (string id in permissionstring.Permissions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { securityid = id; Permission permission = new Permission(); - permission.SiteId = SiteId; - permission.EntityName = EntityName; - permission.EntityId = EntityId; + permission.SiteId = siteId; + permission.EntityName = entityName; + permission.EntityId = entityId; permission.PermissionName = permissionstring.PermissionName; permission.RoleId = null; permission.UserId = null; @@ -177,7 +176,7 @@ namespace Oqtane.Repository if (securityid.StartsWith("!")) { // deny permission - securityid.Replace("!", ""); + securityid = securityid.Replace("!", ""); permission.IsAuthorized = false; } if (securityid.StartsWith("[") && securityid.EndsWith("]")) @@ -189,7 +188,7 @@ namespace Oqtane.Repository else { // role name - Role role = roles.Where(item => item.Name == securityid).SingleOrDefault(); + Role role = roles.SingleOrDefault(item => item.Name == securityid); if (role != null) { permission.RoleId = role.RoleId; diff --git a/Oqtane.Server/Repository/ProfileRepository.cs b/Oqtane.Server/Repository/ProfileRepository.cs index 91062cf9..8577ea78 100644 --- a/Oqtane.Server/Repository/ProfileRepository.cs +++ b/Oqtane.Server/Repository/ProfileRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -14,34 +14,34 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetProfiles(int SiteId) + public IEnumerable GetProfiles(int siteId) { - return _db.Profile.Where(item => item.SiteId == SiteId || item.SiteId == null); + return _db.Profile.Where(item => item.SiteId == siteId || item.SiteId == null); } - public Profile AddProfile(Profile Profile) + public Profile AddProfile(Profile profile) { - _db.Profile.Add(Profile); + _db.Profile.Add(profile); _db.SaveChanges(); - return Profile; + return profile; } - public Profile UpdateProfile(Profile Profile) + public Profile UpdateProfile(Profile profile) { - _db.Entry(Profile).State = EntityState.Modified; + _db.Entry(profile).State = EntityState.Modified; _db.SaveChanges(); - return Profile; + return profile; } - public Profile GetProfile(int ProfileId) + public Profile GetProfile(int profileId) { - return _db.Profile.Find(ProfileId); + return _db.Profile.Find(profileId); } - public void DeleteProfile(int ProfileId) + public void DeleteProfile(int profileId) { - Profile Profile = _db.Profile.Find(ProfileId); - _db.Profile.Remove(Profile); + Profile profile = _db.Profile.Find(profileId); + _db.Profile.Remove(profile); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/RoleRepository.cs b/Oqtane.Server/Repository/RoleRepository.cs index 35aa7fe3..2814d7e0 100644 --- a/Oqtane.Server/Repository/RoleRepository.cs +++ b/Oqtane.Server/Repository/RoleRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -14,40 +14,40 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetRoles(int SiteId) + public IEnumerable GetRoles(int siteId) { - return _db.Role.Where(item => item.SiteId == SiteId); + return _db.Role.Where(item => item.SiteId == siteId); } - public IEnumerable GetRoles(int SiteId, bool IncludeGlobalRoles) + public IEnumerable GetRoles(int siteId, bool includeGlobalRoles) { - return _db.Role.Where(item => item.SiteId == SiteId || item.SiteId == null); + return _db.Role.Where(item => item.SiteId == siteId || item.SiteId == null); } - public Role AddRole(Role Role) + public Role AddRole(Role role) { - _db.Role.Add(Role); + _db.Role.Add(role); _db.SaveChanges(); - return Role; + return role; } - public Role UpdateRole(Role Role) + public Role UpdateRole(Role role) { - _db.Entry(Role).State = EntityState.Modified; + _db.Entry(role).State = EntityState.Modified; _db.SaveChanges(); - return Role; + return role; } - public Role GetRole(int RoleId) + public Role GetRole(int roleId) { - return _db.Role.Find(RoleId); + return _db.Role.Find(roleId); } - public void DeleteRole(int RoleId) + public void DeleteRole(int roleId) { - Role Role = _db.Role.Find(RoleId); - _db.Role.Remove(Role); + Role role = _db.Role.Find(roleId); + _db.Role.Remove(role); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/SettingRepository.cs b/Oqtane.Server/Repository/SettingRepository.cs index 3d670f55..30b7f676 100644 --- a/Oqtane.Server/Repository/SettingRepository.cs +++ b/Oqtane.Server/Repository/SettingRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -14,35 +14,35 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetSettings(string EntityName, int EntityId) + public IEnumerable GetSettings(string entityName, int entityId) { - return _db.Setting.Where(item => item.EntityName == EntityName) - .Where(item => item.EntityId == EntityId); + return _db.Setting.Where(item => item.EntityName == entityName) + .Where(item => item.EntityId == entityId); } - public Setting AddSetting(Setting Setting) + public Setting AddSetting(Setting setting) { - _db.Setting.Add(Setting); + _db.Setting.Add(setting); _db.SaveChanges(); - return Setting; + return setting; } - public Setting UpdateSetting(Setting Setting) + public Setting UpdateSetting(Setting setting) { - _db.Entry(Setting).State = EntityState.Modified; + _db.Entry(setting).State = EntityState.Modified; _db.SaveChanges(); - return Setting; + return setting; } - public Setting GetSetting(int SettingId) + public Setting GetSetting(int settingId) { - return _db.Setting.Find(SettingId); + return _db.Setting.Find(settingId); } - public void DeleteSetting(int SettingId) + public void DeleteSetting(int settingId) { - Setting Setting = _db.Setting.Find(SettingId); - _db.Setting.Remove(Setting); + Setting setting = _db.Setting.Find(settingId); + _db.Setting.Remove(setting); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Repository/SiteRepository.cs b/Oqtane.Server/Repository/SiteRepository.cs index 6b6db2c1..7dead20c 100644 --- a/Oqtane.Server/Repository/SiteRepository.cs +++ b/Oqtane.Server/Repository/SiteRepository.cs @@ -1,12 +1,13 @@ -using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; -using Oqtane.Shared; -using System; using System.Reflection; -using Oqtane.Modules; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Oqtane.Models; +using Oqtane.Modules; +using Oqtane.Shared; +using Module = Oqtane.Models.Module; namespace Oqtane.Repository { @@ -130,19 +131,19 @@ namespace Oqtane.Repository return _db.Site; } - public Site AddSite(Site Site) + public Site AddSite(Site site) { - _db.Site.Add(Site); + _db.Site.Add(site); _db.SaveChanges(); - CreateSite(Site); - return Site; + CreateSite(site); + return site; } - public Site UpdateSite(Site Site) + public Site UpdateSite(Site site) { - _db.Entry(Site).State = EntityState.Modified; + _db.Entry(site).State = EntityState.Modified; _db.SaveChanges(); - return Site; + return site; } public Site GetSite(int siteId) @@ -226,7 +227,7 @@ namespace Oqtane.Repository ModuleDefinition moduledefinition = moduledefinitions.Where(item => item.ModuleDefinitionName == pagetemplatemodule.ModuleDefinitionName).FirstOrDefault(); if (moduledefinition != null) { - Models.Module module = new Models.Module + Module module = new Module { SiteId = site.SiteId, ModuleDefinitionName = pagetemplatemodule.ModuleDefinitionName, diff --git a/Oqtane.Server/Repository/TenantRepository.cs b/Oqtane.Server/Repository/TenantRepository.cs index 8d8c989e..19acf9fa 100644 --- a/Oqtane.Server/Repository/TenantRepository.cs +++ b/Oqtane.Server/Repository/TenantRepository.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Caching.Memory; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; +using Oqtane.Models; namespace Oqtane.Repository { @@ -28,30 +27,30 @@ namespace Oqtane.Repository }); } - public Tenant AddTenant(Tenant Tenant) + public Tenant AddTenant(Tenant tenant) { - _db.Tenant.Add(Tenant); + _db.Tenant.Add(tenant); _db.SaveChanges(); _cache.Remove("tenants"); - return Tenant; + return tenant; } - public Tenant UpdateTenant(Tenant Tenant) + public Tenant UpdateTenant(Tenant tenant) { - _db.Entry(Tenant).State = EntityState.Modified; + _db.Entry(tenant).State = EntityState.Modified; _db.SaveChanges(); _cache.Remove("tenants"); - return Tenant; + return tenant; } - public Tenant GetTenant(int TenantId) + public Tenant GetTenant(int tenantId) { - return _db.Tenant.Find(TenantId); + return _db.Tenant.Find(tenantId); } - public void DeleteTenant(int TenantId) + public void DeleteTenant(int tenantId) { - Tenant tenant = _db.Tenant.Find(TenantId); + Tenant tenant = _db.Tenant.Find(tenantId); _db.Tenant.Remove(tenant); _db.SaveChanges(); _cache.Remove("tenants"); diff --git a/Oqtane.Server/Repository/TenantResolver.cs b/Oqtane.Server/Repository/TenantResolver.cs index 7cbfda35..9760c4e6 100644 --- a/Oqtane.Server/Repository/TenantResolver.cs +++ b/Oqtane.Server/Repository/TenantResolver.cs @@ -1,70 +1,70 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using Microsoft.AspNetCore.Http; -using System; +using Oqtane.Models; using Oqtane.Shared; namespace Oqtane.Repository { public class TenantResolver : ITenantResolver { - private readonly Alias _alias = null; - private readonly Tenant _tenant = null; + private readonly Alias _alias; + private readonly Tenant _tenant; - public TenantResolver(IHttpContextAccessor Accessor, IAliasRepository Aliases, ITenantRepository Tenants, SiteState SiteState) + public TenantResolver(IHttpContextAccessor accessor, IAliasRepository aliasRepository, ITenantRepository tenantRepository, SiteState siteState) { - int aliasid = -1; - string aliasname = ""; + int aliasId = -1; + string aliasName = ""; // get alias identifier based on request context - if (Accessor.HttpContext != null) + if (accessor.HttpContext != null) { // check if an alias is passed as a querystring parameter ( for cross tenant access ) - if (Accessor.HttpContext.Request.Query.ContainsKey("aliasid")) + if (accessor.HttpContext.Request.Query.ContainsKey("aliasid")) { - aliasid = int.Parse(Accessor.HttpContext.Request.Query["aliasid"]); + aliasId = int.Parse(accessor.HttpContext.Request.Query["aliasid"]); } else // get the alias from the request url { - aliasname = Accessor.HttpContext.Request.Host.Value; - string path = Accessor.HttpContext.Request.Path.Value; + aliasName = accessor.HttpContext.Request.Host.Value; + string path = accessor.HttpContext.Request.Path.Value; string[] segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length > 1 && segments[1] == "api" && segments[0] != "~") { - aliasname += "/" + segments[0]; + aliasName += "/" + segments[0]; } - if (aliasname.EndsWith("/")) + if (aliasName.EndsWith("/")) { - aliasname = aliasname.Substring(0, aliasname.Length - 1); + aliasName = aliasName.Substring(0, aliasName.Length - 1); } } } else // background processes can pass in an alias using the SiteState service { - if (SiteState != null) + if (siteState != null) { - aliasid = SiteState.Alias.AliasId; + aliasId = siteState.Alias.AliasId; } } // get the alias and tenant - if (aliasid != -1 || aliasname != "") + if (aliasId != -1 || aliasName != "") { - IEnumerable aliases = Aliases.GetAliases(); // cached - IEnumerable tenants = Tenants.GetTenants(); // cached + IEnumerable aliases = aliasRepository.GetAliases(); // cached + IEnumerable tenants = tenantRepository.GetTenants(); // cached - if (aliasid != -1) + if (aliasId != -1) { - _alias = aliases.Where(item => item.AliasId == aliasid).FirstOrDefault(); + _alias = aliases.FirstOrDefault(item => item.AliasId == aliasId); } else { - _alias = aliases.Where(item => item.Name == aliasname).FirstOrDefault(); + _alias = aliases.FirstOrDefault(item => item.Name == aliasName); } if (_alias != null) { - _tenant = tenants.Where(item => item.TenantId == _alias.TenantId).FirstOrDefault(); + _tenant = tenants.FirstOrDefault(item => item.TenantId == _alias.TenantId); } } } @@ -79,4 +79,4 @@ namespace Oqtane.Repository return _tenant; } } -} \ No newline at end of file +} diff --git a/Oqtane.Server/Repository/ThemeRepository.cs b/Oqtane.Server/Repository/ThemeRepository.cs index 0de27194..3bb3f7e9 100644 --- a/Oqtane.Server/Repository/ThemeRepository.cs +++ b/Oqtane.Server/Repository/ThemeRepository.cs @@ -1,9 +1,8 @@ -using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; -using Oqtane.Models; using System.Reflection; -using System; +using Oqtane.Models; using Oqtane.Themes; namespace Oqtane.Repository @@ -12,17 +11,17 @@ namespace Oqtane.Repository { private List LoadThemes() { - List Themes = new List(); + List themes = new List(); // iterate through Oqtane theme assemblies Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(item => item.FullName.StartsWith("Oqtane.") || item.FullName.Contains(".Theme.")).ToArray(); foreach (Assembly assembly in assemblies) { - Themes = LoadThemesFromAssembly(Themes, assembly); + themes = LoadThemesFromAssembly(themes, assembly); } - return Themes; + return themes; } private List LoadThemesFromAssembly(List themes, Assembly assembly) @@ -36,15 +35,15 @@ namespace Oqtane.Repository string[] typename = themeControlType.AssemblyQualifiedName.Split(',').Select(item => item.Trim()).ToList().ToArray(); string[] segments = typename[0].Split('.'); Array.Resize(ref segments, segments.Length - 1); - string Namespace = string.Join(".", segments); + string @namespace = string.Join(".", segments); - int index = themes.FindIndex(item => item.ThemeName == Namespace); + int index = themes.FindIndex(item => item.ThemeName == @namespace); if (index == -1) { - /// determine if this theme implements ITheme + // determine if this theme implements ITheme Type themetype = assembly.GetTypes() .Where(item => item.Namespace != null) - .Where(item => item.Namespace.StartsWith(Namespace)) + .Where(item => item.Namespace.StartsWith(@namespace)) .Where(item => item.GetInterfaces().Contains(typeof(ITheme))).FirstOrDefault(); if (themetype != null) { @@ -52,7 +51,7 @@ namespace Oqtane.Repository Dictionary properties = (Dictionary)themetype.GetProperty("Properties").GetValue(themeobject); theme = new Theme { - ThemeName = Namespace, + ThemeName = @namespace, Name = GetProperty(properties, "Name"), Version = GetProperty(properties, "Version"), Owner = GetProperty(properties, "Owner"), @@ -70,7 +69,7 @@ namespace Oqtane.Repository { theme = new Theme { - ThemeName = Namespace, + ThemeName = @namespace, Name = themeControlType.Name, Version = new Version(1, 0, 0).ToString(), Owner = "", @@ -85,7 +84,7 @@ namespace Oqtane.Repository }; } themes.Add(theme); - index = themes.FindIndex(item => item.ThemeName == Namespace); + index = themes.FindIndex(item => item.ThemeName == @namespace); } theme = themes[index]; theme.ThemeControls += (themeControlType.FullName + ", " + typename[1] + ";"); @@ -93,7 +92,7 @@ namespace Oqtane.Repository // layouts Type[] layouttypes = assembly.GetTypes() .Where(item => item.Namespace != null) - .Where(item => item.Namespace.StartsWith(Namespace)) + .Where(item => item.Namespace.StartsWith(@namespace)) .Where(item => item.GetInterfaces().Contains(typeof(ILayoutControl))).ToArray(); foreach (Type layouttype in layouttypes) { @@ -107,7 +106,7 @@ namespace Oqtane.Repository // containers Type[] containertypes = assembly.GetTypes() .Where(item => item.Namespace != null) - .Where(item => item.Namespace.StartsWith(Namespace)) + .Where(item => item.Namespace.StartsWith(@namespace)) .Where(item => item.GetInterfaces().Contains(typeof(IContainerControl))).ToArray(); foreach (Type containertype in containertypes) { @@ -124,14 +123,14 @@ namespace Oqtane.Repository return themes; } - private string GetProperty(Dictionary Properties, string Key) + private string GetProperty(Dictionary properties, string key) { - string Value = ""; - if (Properties.ContainsKey(Key)) + string value = ""; + if (properties.ContainsKey(key)) { - Value = Properties[Key]; + value = properties[key]; } - return Value; + return value; } public IEnumerable GetThemes() diff --git a/Oqtane.Server/Repository/UserRepository.cs b/Oqtane.Server/Repository/UserRepository.cs index 16478504..a9e51afe 100644 --- a/Oqtane.Server/Repository/UserRepository.cs +++ b/Oqtane.Server/Repository/UserRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -38,9 +38,9 @@ namespace Oqtane.Repository return _db.User.Find(userId); } - public User GetUser(string Username) + public User GetUser(string username) { - return _db.User.Where(item => item.Username == Username).FirstOrDefault(); + return _db.User.Where(item => item.Username == username).FirstOrDefault(); } public void DeleteUser(int userId) diff --git a/Oqtane.Server/Repository/UserRoleRepository.cs b/Oqtane.Server/Repository/UserRoleRepository.cs index bf4c9676..79f8a629 100644 --- a/Oqtane.Server/Repository/UserRoleRepository.cs +++ b/Oqtane.Server/Repository/UserRoleRepository.cs @@ -1,6 +1,6 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore; using Oqtane.Models; namespace Oqtane.Repository @@ -14,48 +14,48 @@ namespace Oqtane.Repository _db = context; } - public IEnumerable GetUserRoles(int SiteId) + public IEnumerable GetUserRoles(int siteId) { return _db.UserRole .Include(item => item.Role) // eager load roles .Include(item => item.User) // eager load users - .Where(item => item.Role.SiteId == SiteId || item.Role.SiteId == null); + .Where(item => item.Role.SiteId == siteId || item.Role.SiteId == null); } - public IEnumerable GetUserRoles(int UserId, int SiteId) + public IEnumerable GetUserRoles(int userId, int siteId) { - return _db.UserRole.Where(item => item.UserId == UserId) + return _db.UserRole.Where(item => item.UserId == userId) .Include(item => item.Role) // eager load roles .Include(item => item.User) // eager load users - .Where(item => item.Role.SiteId == SiteId || item.Role.SiteId == null); + .Where(item => item.Role.SiteId == siteId || item.Role.SiteId == null); } - public UserRole AddUserRole(UserRole UserRole) + public UserRole AddUserRole(UserRole userRole) { - _db.UserRole.Add(UserRole); + _db.UserRole.Add(userRole); _db.SaveChanges(); - return UserRole; + return userRole; } - public UserRole UpdateUserRole(UserRole UserRole) + public UserRole UpdateUserRole(UserRole userRole) { - _db.Entry(UserRole).State = EntityState.Modified; + _db.Entry(userRole).State = EntityState.Modified; _db.SaveChanges(); - return UserRole; + return userRole; } - public UserRole GetUserRole(int UserRoleId) + public UserRole GetUserRole(int userRoleId) { return _db.UserRole .Include(item => item.Role) // eager load roles .Include(item => item.User) // eager load users - .SingleOrDefault(item => item.UserRoleId == UserRoleId); + .SingleOrDefault(item => item.UserRoleId == userRoleId); } - public void DeleteUserRole(int UserRoleId) + public void DeleteUserRole(int userRoleId) { - UserRole UserRole = _db.UserRole.Find(UserRoleId); - _db.UserRole.Remove(UserRole); + UserRole userRole = _db.UserRole.Find(userRoleId); + _db.UserRole.Remove(userRole); _db.SaveChanges(); } } diff --git a/Oqtane.Server/Security/ClaimsPrincipalFactory.cs b/Oqtane.Server/Security/ClaimsPrincipalFactory.cs index eadf7c6f..1e945938 100644 --- a/Oqtane.Server/Security/ClaimsPrincipalFactory.cs +++ b/Oqtane.Server/Security/ClaimsPrincipalFactory.cs @@ -2,11 +2,11 @@ using Microsoft.Extensions.Options; using System.Security.Claims; using System.Threading.Tasks; -using Oqtane.Repository; using Oqtane.Models; using Oqtane.Shared; using System.Collections.Generic; using System.Linq; +using Oqtane.Repository; namespace Oqtane.Security { diff --git a/Oqtane.Server/Security/IUserPermissions.cs b/Oqtane.Server/Security/IUserPermissions.cs index 92e50d1d..b7964383 100644 --- a/Oqtane.Server/Security/IUserPermissions.cs +++ b/Oqtane.Server/Security/IUserPermissions.cs @@ -5,9 +5,9 @@ namespace Oqtane.Security { public interface IUserPermissions { - bool IsAuthorized(ClaimsPrincipal User, string EntityName, int EntityId, string PermissionName); - bool IsAuthorized(ClaimsPrincipal User, string PermissionName, string Permissions); - User GetUser(ClaimsPrincipal User); + bool IsAuthorized(ClaimsPrincipal user, string entityName, int entityId, string permissionName); + bool IsAuthorized(ClaimsPrincipal user, string permissionName, string permissions); + User GetUser(ClaimsPrincipal user); User GetUser(); } } diff --git a/Oqtane.Server/Security/PermissionHandler.cs b/Oqtane.Server/Security/PermissionHandler.cs index 1f47122b..028df96c 100644 --- a/Oqtane.Server/Security/PermissionHandler.cs +++ b/Oqtane.Server/Security/PermissionHandler.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; -using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; using Oqtane.Shared; namespace Oqtane.Security @@ -25,14 +25,14 @@ namespace Oqtane.Security var ctx = _httpContextAccessor.HttpContext; if (ctx != null && ctx.Request.Query.ContainsKey("entityid")) { - int EntityId = int.Parse(ctx.Request.Query["entityid"]); - if (_userPermissions.IsAuthorized(context.User, requirement.EntityName, EntityId, requirement.PermissionName)) + int entityId = int.Parse(ctx.Request.Query["entityid"]); + if (_userPermissions.IsAuthorized(context.User, requirement.EntityName, entityId, requirement.PermissionName)) { context.Succeed(requirement); } else { - _logger.Log(LogLevel.Error, this, LogFunction.Security, "User {User} Does Not Have {PermissionName} Permission For {EntityName}:{EntityId}", context.User, requirement.PermissionName, requirement.EntityName, EntityId); + _logger.Log(LogLevel.Error, this, LogFunction.Security, "User {User} Does Not Have {PermissionName} Permission For {EntityName}:{EntityId}", context.User, requirement.PermissionName, requirement.EntityName, entityId); } } return Task.CompletedTask; diff --git a/Oqtane.Server/Security/UserPermissions.cs b/Oqtane.Server/Security/UserPermissions.cs index 3ec92160..2e20b062 100644 --- a/Oqtane.Server/Security/UserPermissions.cs +++ b/Oqtane.Server/Security/UserPermissions.cs @@ -1,8 +1,8 @@ using Microsoft.AspNetCore.Http; using Oqtane.Models; -using Oqtane.Repository; using System.Linq; using System.Security.Claims; +using Oqtane.Repository; namespace Oqtane.Security { @@ -17,41 +17,40 @@ namespace Oqtane.Security _accessor = accessor; } - public bool IsAuthorized(ClaimsPrincipal User, string EntityName, int EntityId, string PermissionName) + public bool IsAuthorized(ClaimsPrincipal user, string entityName, int entityId, string permissionName) { - return IsAuthorized(User, PermissionName, _permissions.EncodePermissions(EntityId, _permissions.GetPermissions(EntityName, EntityId, PermissionName).ToList())); + return IsAuthorized(user, permissionName, _permissions.EncodePermissions(entityId, _permissions.GetPermissions(entityName, entityId, permissionName).ToList())); } - public bool IsAuthorized(ClaimsPrincipal User, string PermissionName, string Permissions) + public bool IsAuthorized(ClaimsPrincipal user, string permissionName, string permissions) { - return UserSecurity.IsAuthorized(GetUser(User), PermissionName, Permissions); + return UserSecurity.IsAuthorized(GetUser(user), permissionName, permissions); } - public User GetUser(ClaimsPrincipal User) + public User GetUser(ClaimsPrincipal user) { - User user = new User(); - user.Username = ""; - user.IsAuthenticated = false; - user.UserId = -1; - user.Roles = ""; + User resultUser = new User(); + resultUser.Username = ""; + resultUser.IsAuthenticated = false; + resultUser.UserId = -1; + resultUser.Roles = ""; - if (User != null) + if (user == null) return resultUser; + + resultUser.Username = user.Identity.Name; + resultUser.IsAuthenticated = user.Identity.IsAuthenticated; + var idclaim = user.Claims.FirstOrDefault(item => item.Type == ClaimTypes.PrimarySid); + if (idclaim != null) { - user.Username = User.Identity.Name; - user.IsAuthenticated = User.Identity.IsAuthenticated; - var idclaim = User.Claims.Where(item => item.Type == ClaimTypes.PrimarySid).FirstOrDefault(); - if (idclaim != null) + resultUser.UserId = int.Parse(idclaim.Value); + foreach (var claim in user.Claims.Where(item => item.Type == ClaimTypes.Role)) { - user.UserId = int.Parse(idclaim.Value); - foreach (var claim in User.Claims.Where(item => item.Type == ClaimTypes.Role)) - { - user.Roles += claim.Value + ";"; - } - if (user.Roles != "") user.Roles = ";" + user.Roles; + resultUser.Roles += claim.Value + ";"; } - } - return user; + if (resultUser.Roles != "") resultUser.Roles = ";" + resultUser.Roles; + } + return resultUser; } public User GetUser() diff --git a/Oqtane.Server/Startup.cs b/Oqtane.Server/Startup.cs index acb3b811..79a2d31c 100644 --- a/Oqtane.Server/Startup.cs +++ b/Oqtane.Server/Startup.cs @@ -1,34 +1,27 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.ResponseCompression; // needed for WASM -using Microsoft.Extensions.DependencyInjection; -using System.Linq; -using Microsoft.Extensions.Configuration; -using Microsoft.EntityFrameworkCore; -using Microsoft.AspNetCore.Http; using System; -using System.Reflection; -using Microsoft.Extensions.Hosting; -using Oqtane.Modules; -using Oqtane.Repository; using System.IO; -using System.Runtime.Loader; -using Oqtane.Services; +using System.Linq; using System.Net.Http; -using Microsoft.AspNetCore.Components; -using Oqtane.Shared; -using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; -using System.Collections.Generic; -using Microsoft.OpenApi.Models; -using Oqtane.Security; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication; -using System.Net; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.OpenApi.Models; using Oqtane.Infrastructure; +using Oqtane.Infrastructure.Interfaces; +using Oqtane.Repository; +using Oqtane.Security; +using Oqtane.Services; +using Oqtane.Shared; // needed for WASM -namespace Oqtane.Server +namespace Oqtane { public class Startup { @@ -59,10 +52,10 @@ namespace Oqtane.Server // setup HttpClient for server side in a client side compatible fashion ( with auth cookie ) if (!services.Any(x => x.ServiceType == typeof(HttpClient))) { - services.AddScoped(s => + services.AddScoped(s => { // creating the URI helper needs to wait until the JS Runtime is initialized, so defer it. - var NavigationManager = s.GetRequiredService(); + var navigationManager = s.GetRequiredService(); var httpContextAccessor = s.GetRequiredService(); var authToken = httpContextAccessor.HttpContext.Request.Cookies[".AspNetCore.Identity.Application"]; var client = new HttpClient(new HttpClientHandler { UseCookies = false }); @@ -70,7 +63,7 @@ namespace Oqtane.Server { client.DefaultRequestHeaders.Add("Cookie", ".AspNetCore.Identity.Application=" + authToken); } - client.BaseAddress = new Uri(NavigationManager.Uri); + client.BaseAddress = new Uri(navigationManager.Uri); return client; }); } @@ -78,13 +71,13 @@ namespace Oqtane.Server // register authorization services services.AddAuthorizationCore(options => { - options.AddPolicy("ViewPage", policy => policy.Requirements.Add(new PermissionRequirement("Page", PermissionNames.View))); - options.AddPolicy("EditPage", policy => policy.Requirements.Add(new PermissionRequirement("Page", PermissionNames.Edit))); - options.AddPolicy("ViewModule", policy => policy.Requirements.Add(new PermissionRequirement("Module", PermissionNames.View))); - options.AddPolicy("EditModule", policy => policy.Requirements.Add(new PermissionRequirement("Module", PermissionNames.Edit))); - options.AddPolicy("ViewFolder", policy => policy.Requirements.Add(new PermissionRequirement("Folder", PermissionNames.View))); - options.AddPolicy("EditFolder", policy => policy.Requirements.Add(new PermissionRequirement("Folder", PermissionNames.Edit))); - options.AddPolicy("ListFolder", policy => policy.Requirements.Add(new PermissionRequirement("Folder", "List"))); + options.AddPolicy("ViewPage", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Page, PermissionNames.View))); + options.AddPolicy("EditPage", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Page, PermissionNames.Edit))); + options.AddPolicy("ViewModule", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Module, PermissionNames.View))); + options.AddPolicy("EditModule", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Module, PermissionNames.Edit))); + options.AddPolicy("ViewFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.View))); + options.AddPolicy("EditFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.Edit))); + options.AddPolicy("ListFolder", policy => policy.Requirements.Add(new PermissionRequirement(EntityNames.Folder, PermissionNames.Browse))); }); // register scoped core services @@ -160,7 +153,7 @@ namespace Oqtane.Server services.AddTransient, ClaimsPrincipalFactory>(); // register singleton scoped core services - services.AddSingleton(Configuration); + services.AddSingleton(Configuration); services.AddSingleton(); services.AddSingleton(); @@ -206,7 +199,7 @@ namespace Oqtane.Server } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IInstallationManager InstallationManager) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IInstallationManager installationManager) { if (env.IsDevelopment()) { @@ -219,7 +212,7 @@ namespace Oqtane.Server } // install any modules or themes - InstallationManager.InstallPackages("Modules,Themes", false); + installationManager.InstallPackages("Modules,Themes", false); app.UseHttpsRedirection(); diff --git a/Oqtane.Shared/Models/Log.cs b/Oqtane.Shared/Models/Log.cs index 1e8aa8c8..a1ff4c16 100644 --- a/Oqtane.Shared/Models/Log.cs +++ b/Oqtane.Shared/Models/Log.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel.DataAnnotations.Schema; namespace Oqtane.Models { diff --git a/Oqtane.Shared/Models/Module.cs b/Oqtane.Shared/Models/Module.cs index 0466c326..927377a0 100644 --- a/Oqtane.Shared/Models/Module.cs +++ b/Oqtane.Shared/Models/Module.cs @@ -1,7 +1,5 @@ -using Oqtane.Modules; -using Oqtane.Shared; +using Oqtane.Shared; using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace Oqtane.Models diff --git a/Oqtane.Shared/Security/UserSecurity.cs b/Oqtane.Shared/Security/UserSecurity.cs index 01bbb7e7..a8e85304 100644 --- a/Oqtane.Shared/Security/UserSecurity.cs +++ b/Oqtane.Shared/Security/UserSecurity.cs @@ -9,21 +9,21 @@ namespace Oqtane.Security { public class UserSecurity { - public static List GetPermissionStrings(string PermissionStrings) + public static List GetPermissionStrings(string permissionStrings) { - return JsonSerializer.Deserialize>(PermissionStrings); + return JsonSerializer.Deserialize>(permissionStrings); } - public static string SetPermissionStrings(List PermissionStrings) + public static string SetPermissionStrings(List permissionStrings) { - return JsonSerializer.Serialize(PermissionStrings); + return JsonSerializer.Serialize(permissionStrings); } - public static string GetPermissions(string PermissionName, string PermissionStrings) + public static string GetPermissions(string permissionName, string permissionStrings) { string permissions = ""; - List permissionstrings = JsonSerializer.Deserialize>(PermissionStrings); - PermissionString permissionstring = permissionstrings.FirstOrDefault(item => item.PermissionName == PermissionName); + List permissionstrings = JsonSerializer.Deserialize>(permissionStrings); + PermissionString permissionstring = permissionstrings.FirstOrDefault(item => item.PermissionName == permissionName); if (permissionstring != null) { permissions = permissionstring.Permissions; @@ -31,68 +31,68 @@ namespace Oqtane.Security return permissions; } - public static bool IsAuthorized(User User, string PermissionName, string PermissionStrings) + public static bool IsAuthorized(User user, string permissionName, string permissionStrings) { - return IsAuthorized(User, GetPermissions(PermissionName, PermissionStrings)); + return IsAuthorized(user, GetPermissions(permissionName, permissionStrings)); } // permissions are stored in the format "!rolename1;![userid1];rolename2;rolename3;[userid2];[userid3]" where "!" designates Deny permissions - public static bool IsAuthorized(User User, string Permissions) + public static bool IsAuthorized(User user, string permissions) { bool authorized = false; - if (Permissions != "") + if (permissions != "") { - if (User == null) + if (user == null) { - authorized = IsAuthorized(-1, "", Permissions); // user is not authenticated but may have access to resource + authorized = IsAuthorized(-1, "", permissions); // user is not authenticated but may have access to resource } else { - authorized = IsAuthorized(User.UserId, User.Roles, Permissions); + authorized = IsAuthorized(user.UserId, user.Roles, permissions); } } return authorized; } - private static bool IsAuthorized(int UserId, string Roles, string Permissions) + private static bool IsAuthorized(int userId, string roles, string permissions) { - bool IsAuthorized = false; + bool isAuthorized = false; - if (Permissions != null) + if (permissions != null) { - foreach (string permission in Permissions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (string permission in permissions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { - bool? allowed = VerifyPermission(UserId, Roles, permission); + bool? allowed = VerifyPermission(userId, roles, permission); if (allowed.HasValue) { - IsAuthorized = allowed.Value; + isAuthorized = allowed.Value; break; } } } - return IsAuthorized; + return isAuthorized; } - private static bool? VerifyPermission(int UserId, string Roles, string Permission) + private static bool? VerifyPermission(int userId, string roles, string permission) { bool? allowed = null; //permissions strings are encoded with deny permissions at the beginning and grant permissions at the end for optimal performance - if (!String.IsNullOrEmpty(Permission)) + if (!String.IsNullOrEmpty(permission)) { // deny permission - if (Permission.StartsWith("!")) + if (permission.StartsWith("!")) { - string denyRole = Permission.Replace("!", ""); - if (denyRole == Constants.AllUsersRole || IsAllowed(UserId, Roles, denyRole)) + string denyRole = permission.Replace("!", ""); + if (denyRole == Constants.AllUsersRole || IsAllowed(userId, roles, denyRole)) { allowed = false; } } else // grant permission { - if (Permission == Constants.AllUsersRole || IsAllowed(UserId, Roles, Permission)) + if (permission == Constants.AllUsersRole || IsAllowed(userId, roles, permission)) { allowed = true; } @@ -101,16 +101,16 @@ namespace Oqtane.Security return allowed; } - private static bool IsAllowed(int UserId, string Roles, string Permission) + private static bool IsAllowed(int userId, string roles, string permission) { - if ("[" + UserId + "]" == Permission) + if ("[" + userId + "]" == permission) { return true; } - if (Roles != null) + if (roles != null) { - return Roles.IndexOf(";" + Permission + ";") != -1; + return roles.IndexOf(";" + permission + ";") != -1; } return false; } diff --git a/Oqtane.Upgrade/Program.cs b/Oqtane.Upgrade/Program.cs index 70ede475..8aa70d3b 100644 --- a/Oqtane.Upgrade/Program.cs +++ b/Oqtane.Upgrade/Program.cs @@ -125,27 +125,25 @@ namespace Oqtane.Upgrade } } } - - return; } private static bool CanAccessFiles(List files, string folder) { // ensure files are not locked by another process - the shutdownTimeLimit defines the duration for app shutdown - bool canaccess = true; + bool canAccess = true; FileStream stream = null; int i = 0; - while (i < (files.Count - 1) && canaccess) + while (i < (files.Count - 1) && canAccess) { string filepath = Path.Combine(folder, Path.GetFileName(files[i])); int attempts = 0; bool locked = true; // try up to 30 times - while (attempts < 30 && locked == true) + while (attempts < 30 && locked) { try { - stream = System.IO.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.None); + stream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.None); locked = false; } catch // file is locked by another process @@ -154,20 +152,17 @@ namespace Oqtane.Upgrade } finally { - if (stream != null) - { - stream.Close(); - } + stream?.Close(); } attempts += 1; } - if (locked && canaccess) + if (locked) { - canaccess = false; + canAccess = false; } i += 1; } - return canaccess; + return canAccess; } } } From cf6643aef32dc2a14689c21c5eb7064b0b591d91 Mon Sep 17 00:00:00 2001 From: Pavel Vesely Date: Sun, 15 Mar 2020 15:18:32 +0100 Subject: [PATCH 3/3] Client fixes Client is partially done. 227 warnings left out of 1500 I like Rider --- Oqtane.Client/Modules/Admin/Files/Index.razor | 2 - Oqtane.Client/Modules/Admin/Pages/Add.razor | 148 +++++------ Oqtane.Client/Modules/Admin/Pages/Edit.razor | 230 +++++++++--------- Oqtane.Client/Modules/Admin/Site/Index.razor | 186 +++++++------- Oqtane.Client/Modules/Admin/Sites/Edit.razor | 162 ++++++------ Oqtane.Client/Modules/Admin/Sites/Index.razor | 34 +-- .../Modules/Controls/ActionDialog.razor | 18 +- .../Modules/Controls/ActionLink.razor | 38 +-- .../Modules/Controls/AuditInfo.razor | 32 +-- .../Modules/Controls/FileManager.razor | 171 +++++++------ Oqtane.Client/Modules/Controls/Pager.razor | 84 +++---- .../Modules/Controls/PermissionGrid.razor | 98 ++++---- .../Modules/Controls/RichTextEditor.razor | 78 +++--- .../Modules/Controls/TabControl.razor | 8 +- .../Modules/Controls/TriStateCheckBox.razor | 34 +-- Oqtane.Client/Modules/HtmlText/Edit.razor | 4 +- Oqtane.Client/Modules/ModuleBase.cs | 1 + Oqtane.Client/Program.cs | 4 +- .../IdentityAuthenticationStateProvider.cs | 2 +- Oqtane.Client/Services/AliasService.cs | 22 +- Oqtane.Client/Services/FileService.cs | 57 +++-- Oqtane.Client/Services/FolderService.cs | 47 ++-- Oqtane.Client/Services/InstallationService.cs | 10 +- .../Services/Interfaces/IAliasService.cs | 10 +- .../Services/Interfaces/IFileService.cs | 20 +- .../Services/Interfaces/IFolderService.cs | 12 +- .../Services/Interfaces/IJobLogService.cs | 8 +- .../Services/Interfaces/IJobService.cs | 12 +- .../Services/Interfaces/ILogService.cs | 9 +- .../Interfaces/IModuleDefinitionService.cs | 10 +- .../Services/Interfaces/IModuleService.cs | 14 +- .../Interfaces/INotificationService.cs | 10 +- .../Services/Interfaces/IPackageService.cs | 4 +- .../Services/Interfaces/IPageModuleService.cs | 13 +- .../Services/Interfaces/IPageService.cs | 18 +- .../Services/Interfaces/IProfileService.cs | 10 +- .../Services/Interfaces/IRoleService.cs | 10 +- .../Services/Interfaces/ISettingService.cs | 42 ++-- .../Services/Interfaces/ISiteService.cs | 10 +- .../Services/Interfaces/ITenantService.cs | 8 +- .../Services/Interfaces/IThemeService.cs | 8 +- .../Services/Interfaces/IUserRoleService.cs | 10 +- .../Services/Interfaces/IUserService.cs | 23 +- Oqtane.Client/Services/JobLogService.cs | 22 +- Oqtane.Client/Services/JobService.cs | 30 +-- Oqtane.Client/Services/LogService.cs | 29 +-- .../Services/ModuleDefinitionService.cs | 28 +-- Oqtane.Client/Services/ModuleService.cs | 30 +-- Oqtane.Client/Services/NotificationService.cs | 26 +- Oqtane.Client/Services/PackageService.cs | 10 +- Oqtane.Client/Services/PageModuleService.cs | 28 +-- Oqtane.Client/Services/PageService.cs | 58 ++--- Oqtane.Client/Services/ProfileService.cs | 24 +- Oqtane.Client/Services/RoleService.cs | 24 +- Oqtane.Client/Services/SettingService.cs | 106 ++++---- Oqtane.Client/Services/SiteService.cs | 22 +- Oqtane.Client/Services/TenantService.cs | 20 +- Oqtane.Client/Services/ThemeService.cs | 28 +-- Oqtane.Client/Services/UserRoleService.cs | 23 +- Oqtane.Client/Services/UserService.cs | 46 ++-- .../Themes/Controls/ControlPanel.razor | 1 + Oqtane.Client/Themes/ThemeBase.cs | 2 +- Oqtane.Client/UI/ContainerBuilder.razor | 10 +- Oqtane.Client/UI/Installer.razor | 102 ++++---- Oqtane.Client/UI/Interop.cs | 2 +- Oqtane.Client/UI/ModuleInstance.razor | 24 +- Oqtane.Client/UI/Pane.razor | 48 ++-- Oqtane.Client/UI/RichTextEditorInterop.cs | 10 +- Oqtane.Client/UI/SiteRouter.razor | 37 +-- Oqtane.Server/Controllers/AliasController.cs | 1 + Oqtane.Server/Controllers/FileController.cs | 1 + Oqtane.Server/Controllers/FolderController.cs | 1 + Oqtane.Server/Controllers/JobController.cs | 1 + Oqtane.Server/Controllers/JobLogController.cs | 1 + Oqtane.Server/Controllers/ModuleController.cs | 1 + .../Controllers/ModuleDefinitionController.cs | 1 + .../Controllers/NotificationController.cs | 1 + Oqtane.Server/Controllers/PageController.cs | 1 + .../Controllers/PageModuleController.cs | 1 + .../Controllers/ProfileController.cs | 1 + Oqtane.Server/Controllers/RoleController.cs | 1 + .../Controllers/SettingController.cs | 1 + Oqtane.Server/Controllers/SiteController.cs | 1 + Oqtane.Server/Controllers/TenantController.cs | 1 + Oqtane.Server/Controllers/ThemeController.cs | 1 + Oqtane.Server/Controllers/UserController.cs | 1 + .../Controllers/UserRoleController.cs | 1 + .../Infrastructure/Interfaces/ILogManager.cs | 1 + Oqtane.Server/Infrastructure/LogManager.cs | 1 + .../Controllers/HtmlTextController.cs | 1 + Oqtane.Server/Security/PermissionHandler.cs | 1 + Oqtane.Shared/Enums/LogFunction.cs | 2 +- 92 files changed, 1283 insertions(+), 1262 deletions(-) diff --git a/Oqtane.Client/Modules/Admin/Files/Index.razor b/Oqtane.Client/Modules/Admin/Files/Index.razor index 6dd27603..efe9c33a 100644 --- a/Oqtane.Client/Modules/Admin/Files/Index.razor +++ b/Oqtane.Client/Modules/Admin/Files/Index.razor @@ -54,7 +54,6 @@ List _folders; int _folderId = -1; List _files; - Uri _uri; protected override async Task OnParametersSetAsync() { @@ -66,7 +65,6 @@ _folderId = _folders[0].FolderId; await GetFiles(); } - _uri = new Uri(NavigationManager.Uri); } catch (Exception ex) { diff --git a/Oqtane.Client/Modules/Admin/Pages/Add.razor b/Oqtane.Client/Modules/Admin/Pages/Add.razor index 17a785dc..e912cc9d 100644 --- a/Oqtane.Client/Modules/Admin/Pages/Add.razor +++ b/Oqtane.Client/Modules/Admin/Pages/Add.razor @@ -4,7 +4,7 @@ @inject IPageService PageService @inject IThemeService ThemeService -@if (Themes != null) +@if (_themeList != null) { @@ -12,7 +12,7 @@ @@ -20,7 +20,7 @@ @@ -30,7 +30,7 @@ @@ -137,7 +137,7 @@
- +
- +
- - @if (children != null && children.Count > 0) + @if (_children != null && _children.Count > 0) { } - @if (children != null && children.Count > 0 && (insert == "<" || insert == ">")) + @if (_children != null && _children.Count > 0 && (_insert == "<" || _insert == ">")) { - - @foreach (Page page in children) + @foreach (Page page in _children) { } @@ -68,7 +68,7 @@ - @@ -79,7 +79,7 @@ - @@ -90,7 +90,7 @@ - @@ -103,7 +103,7 @@ - - @foreach (KeyValuePair panelayout in panelayouts) + @foreach (KeyValuePair panelayout in _panelayouts) { } @@ -129,7 +129,7 @@ - +
- +
@@ -148,45 +148,45 @@ @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - Dictionary themes = new Dictionary(); - Dictionary panelayouts = new Dictionary(); + Dictionary _themes = new Dictionary(); + Dictionary _panelayouts = new Dictionary(); - List Themes; - List pages; - string name; - string path = ""; - string parentid; - string insert = ">>"; - List children; - int childid = -1; - string isnavigation = "True"; - string ispersonalizable = "False"; - string mode = "view"; - string themetype = ""; - string layouttype = ""; - string icon = ""; - string permissions = ""; + List _themeList; + List _pageList; + string _name; + string _path = ""; + string _parentid; + string _insert = ">>"; + List _children; + int _childid = -1; + string _isnavigation = "True"; + string _ispersonalizable = "False"; + string _mode = "view"; + string _themetype = ""; + string _layouttype = ""; + string _icon = ""; + string _permissions = ""; - PermissionGrid permissiongrid; + PermissionGrid _permissionGrid; protected override async Task OnInitializedAsync() { try { - Themes = await ThemeService.GetThemesAsync(); - pages = PageState.Pages; - children = PageState.Pages.Where(item => item.ParentId == null).ToList(); + _themeList = await ThemeService.GetThemesAsync(); + _pageList = PageState.Pages; + _children = PageState.Pages.Where(item => item.ParentId == null).ToList(); - themes = ThemeService.GetThemeTypes(Themes); - themetype = PageState.Site.DefaultThemeType; + _themes = ThemeService.GetThemeTypes(_themeList); + _themetype = PageState.Site.DefaultThemeType; - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); - layouttype = PageState.Site.DefaultLayoutType; + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); + _layouttype = PageState.Site.DefaultLayoutType; List permissionstrings = new List(); permissionstrings.Add(new PermissionString { PermissionName = PermissionNames.View, Permissions = Constants.AdminRole }); permissionstrings.Add(new PermissionString { PermissionName = PermissionNames.Edit, Permissions = Constants.AdminRole }); - permissions = UserSecurity.SetPermissionStrings(permissionstrings); + _permissions = UserSecurity.SetPermissionStrings(permissionstrings); } catch (Exception ex) { @@ -199,20 +199,20 @@ { try { - parentid = (string)e.Value; - if (parentid == "-1") + _parentid = (string)e.Value; + if (_parentid == "-1") { - children = PageState.Pages.Where(item => item.ParentId == null).ToList(); + _children = PageState.Pages.Where(item => item.ParentId == null).ToList(); } else { - children = PageState.Pages.Where(item => item.ParentId == int.Parse(parentid)).ToList(); + _children = PageState.Pages.Where(item => item.ParentId == int.Parse(_parentid)).ToList(); } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Child Pages For Parent {PageId} {Error}", parentid, ex.Message); + await logger.LogError(ex, "Error Loading Child Pages For Parent {PageId} {Error}", _parentid, ex.Message); AddModuleMessage("Error Loading Child Pages For Parent", MessageType.Error); } } @@ -221,20 +221,20 @@ { try { - themetype = (string)e.Value; - if (themetype != "") + _themetype = (string)e.Value; + if (_themetype != "") { - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); } else { - panelayouts = new Dictionary(); + _panelayouts = new Dictionary(); } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", themetype, ex.Message); + await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", _themetype, ex.Message); AddModuleMessage("Error Loading Pane Layouts For Theme", MessageType.Error); } } @@ -244,61 +244,61 @@ Page page = null; try { - if (name != "" && !string.IsNullOrEmpty(themetype) && (panelayouts.Count == 0 || !string.IsNullOrEmpty(layouttype))) + if (_name != "" && !string.IsNullOrEmpty(_themetype) && (_panelayouts.Count == 0 || !string.IsNullOrEmpty(_layouttype))) { page = new Page(); page.SiteId = PageState.Page.SiteId; - page.Name = name; - if (path == "") + page.Name = _name; + if (_path == "") { - path = name; + _path = _name; } - if (path.Contains("/")) + if (_path.Contains("/")) { - path = path.Substring(path.LastIndexOf("/") + 1); + _path = _path.Substring(_path.LastIndexOf("/") + 1); } - if (string.IsNullOrEmpty(parentid)) + if (string.IsNullOrEmpty(_parentid)) { page.ParentId = null; - page.Path = Utilities.GetFriendlyUrl(path); + page.Path = Utilities.GetFriendlyUrl(_path); } else { - page.ParentId = Int32.Parse(parentid); + page.ParentId = Int32.Parse(_parentid); Page parent = PageState.Pages.Where(item => item.PageId == page.ParentId).FirstOrDefault(); if (parent.Path == "") { - page.Path = Utilities.GetFriendlyUrl(parent.Name) + "/" + Utilities.GetFriendlyUrl(path); + page.Path = Utilities.GetFriendlyUrl(parent.Name) + "/" + Utilities.GetFriendlyUrl(_path); } else { - page.Path = parent.Path + "/" + Utilities.GetFriendlyUrl(path); + page.Path = parent.Path + "/" + Utilities.GetFriendlyUrl(_path); } } Page child; - switch (insert) + switch (_insert) { case "<<": page.Order = 0; break; case "<": - child = PageState.Pages.Where(item => item.PageId == childid).FirstOrDefault(); + child = PageState.Pages.Where(item => item.PageId == _childid).FirstOrDefault(); page.Order = child.Order - 1; break; case ">": - child = PageState.Pages.Where(item => item.PageId == childid).FirstOrDefault(); + child = PageState.Pages.Where(item => item.PageId == _childid).FirstOrDefault(); page.Order = child.Order + 1; break; case ">>": page.Order = int.MaxValue; break; } - page.IsNavigation = (isnavigation == null ? true : Boolean.Parse(isnavigation)); - page.EditMode = (mode == "edit" ? true : false); - page.ThemeType = themetype; - page.LayoutType = (layouttype == null ? "" : layouttype); - page.Icon = (icon == null ? "" : icon); - page.Permissions = permissiongrid.GetPermissions(); + page.IsNavigation = (_isnavigation == null ? true : Boolean.Parse(_isnavigation)); + page.EditMode = (_mode == "edit" ? true : false); + page.ThemeType = _themetype; + page.LayoutType = (_layouttype == null ? "" : _layouttype); + page.Icon = (_icon == null ? "" : _icon); + page.Permissions = _permissionGrid.GetPermissions(); if (page.ThemeType == PageState.Site.DefaultThemeType) { @@ -308,7 +308,7 @@ { page.LayoutType = ""; } - page.IsPersonalizable = (ispersonalizable == null ? false : Boolean.Parse(ispersonalizable)); + page.IsPersonalizable = (_ispersonalizable == null ? false : Boolean.Parse(_ispersonalizable)); page.UserId = null; page = await PageService.AddPageAsync(page); diff --git a/Oqtane.Client/Modules/Admin/Pages/Edit.razor b/Oqtane.Client/Modules/Admin/Pages/Edit.razor index cad64681..ba2eef54 100644 --- a/Oqtane.Client/Modules/Admin/Pages/Edit.razor +++ b/Oqtane.Client/Modules/Admin/Pages/Edit.razor @@ -4,7 +4,7 @@ @inject IPageService PageService @inject IThemeService ThemeService -@if (Themes != null) +@if (_themeList != null) { @@ -12,7 +12,7 @@ @@ -20,7 +20,7 @@ @@ -30,9 +30,9 @@ @@ -155,7 +155,7 @@
- +
- +
- + @if (_parentid == _currentparentid) { } - @if (children != null && children.Count > 0) + @if (_children != null && _children.Count > 0) { } - @if (children != null && children.Count > 0 && (insert == "<" || insert == ">")) + @if (_children != null && _children.Count > 0 && (_insert == "<" || _insert == ">")) { - - @foreach (Page page in children) + @foreach (Page page in _children) { } @@ -79,7 +79,7 @@ - @@ -90,7 +90,7 @@ - @@ -101,7 +101,7 @@ - @@ -114,9 +114,9 @@ - - @foreach (KeyValuePair panelayout in panelayouts) + @foreach (KeyValuePair panelayout in _panelayouts) { } @@ -147,7 +147,7 @@ - +
- +
@@ -163,89 +163,91 @@ Cancel

- + } @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - Dictionary themes = new Dictionary(); - Dictionary panelayouts = new Dictionary(); + Dictionary _themes = new Dictionary(); + Dictionary _panelayouts = new Dictionary(); - List Themes; - List pages; - int PageId; - string name; - string path; - string currentparentid; - string parentid; - string insert = "="; - List children; - int childid = -1; - string isnavigation; - string ispersonalizable; - string mode; - string themetype; - string layouttype; - string icon; - string permissions; - string createdby; - DateTime createdon; - string modifiedby; - DateTime modifiedon; - string deletedby; - DateTime? deletedon; + List _themeList; + List _pageList; + int _pageId; + string _name; + string _path; + string _currentparentid; + string _parentid; + string _insert = "="; + List _children; + int _childid = -1; + string _isnavigation; + string _ispersonalizable; + string _mode; + string _themetype; + string _layouttype; + string _icon; + string _permissions; + string _createdby; + DateTime _createdon; + string _modifiedby; + DateTime _modifiedon; + string _deletedby; + DateTime? _deletedon; - PermissionGrid permissiongrid; +#pragma warning disable 649 + PermissionGrid _permissionGrid; +#pragma warning restore 649 protected override async Task OnInitializedAsync() { try { - Themes = await ThemeService.GetThemesAsync(); - pages = PageState.Pages; - children = PageState.Pages.Where(item => item.ParentId == null).ToList(); + _themeList = await ThemeService.GetThemesAsync(); + _pageList = PageState.Pages; + _children = PageState.Pages.Where(item => item.ParentId == null).ToList(); - themes = ThemeService.GetThemeTypes(Themes); + _themes = ThemeService.GetThemeTypes(_themeList); - PageId = Int32.Parse(PageState.QueryString["id"]); - Page page = PageState.Pages.FirstOrDefault(item => item.PageId == PageId); + _pageId = Int32.Parse(PageState.QueryString["id"]); + Page page = PageState.Pages.FirstOrDefault(item => item.PageId == _pageId); if (page != null) { - name = page.Name; - path = page.Path; - if (path.Contains("/")) + _name = page.Name; + _path = page.Path; + if (_path.Contains("/")) { - path = path.Substring(path.LastIndexOf("/") + 1); + _path = _path.Substring(_path.LastIndexOf("/") + 1); } if (page.ParentId == null) { - parentid = ""; + _parentid = ""; } else { - parentid = page.ParentId.ToString(); + _parentid = page.ParentId.ToString(); } - currentparentid = parentid; - isnavigation = page.IsNavigation.ToString(); - ispersonalizable = page.IsPersonalizable.ToString(); - mode = (page.EditMode) ? "edit" : "view"; - themetype = page.ThemeType; - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); - layouttype = page.LayoutType; - icon = page.Icon; - permissions = page.Permissions; - createdby = page.CreatedBy; - createdon = page.CreatedOn; - modifiedby = page.ModifiedBy; - modifiedon = page.ModifiedOn; - deletedby = page.DeletedBy; - deletedon = page.DeletedOn; + _currentparentid = _parentid; + _isnavigation = page.IsNavigation.ToString(); + _ispersonalizable = page.IsPersonalizable.ToString(); + _mode = (page.EditMode) ? "edit" : "view"; + _themetype = page.ThemeType; + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); + _layouttype = page.LayoutType; + _icon = page.Icon; + _permissions = page.Permissions; + _createdby = page.CreatedBy; + _createdon = page.CreatedOn; + _modifiedby = page.ModifiedBy; + _modifiedon = page.ModifiedOn; + _deletedby = page.DeletedBy; + _deletedon = page.DeletedOn; } } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Page {PageId} {Error}", PageId, ex.Message); + await logger.LogError(ex, "Error Loading Page {PageId} {Error}", _pageId, ex.Message); AddModuleMessage("Error Loading Page", MessageType.Error); } } @@ -254,28 +256,28 @@ { try { - parentid = (string)e.Value; - if (parentid == "-1") + _parentid = (string)e.Value; + if (_parentid == "-1") { - children = PageState.Pages.Where(item => item.ParentId == null).ToList(); + _children = PageState.Pages.Where(item => item.ParentId == null).ToList(); } else { - children = PageState.Pages.Where(item => item.ParentId == int.Parse(parentid)).ToList(); + _children = PageState.Pages.Where(item => item.ParentId == int.Parse(_parentid)).ToList(); } - if (parentid == currentparentid) + if (_parentid == _currentparentid) { - insert = "="; + _insert = "="; } else { - insert = ">>"; + _insert = ">>"; } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Child Pages For Parent {PageId} {Error}", parentid, ex.Message); + await logger.LogError(ex, "Error Loading Child Pages For Parent {PageId} {Error}", _parentid, ex.Message); AddModuleMessage("Error Loading Child Pages For Parent", MessageType.Error); } } @@ -284,20 +286,20 @@ { try { - themetype = (string)e.Value; - if (themetype != "") + _themetype = (string)e.Value; + if (_themetype != "") { - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); } else { - panelayouts = new Dictionary(); + _panelayouts = new Dictionary(); } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", themetype, ex.Message); + await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", _themetype, ex.Message); AddModuleMessage("Error Loading Pane Layouts For Theme", MessageType.Error); } } @@ -307,52 +309,52 @@ Page page = null; try { - if (name != "" && !string.IsNullOrEmpty(themetype) && (panelayouts.Count == 0 || !string.IsNullOrEmpty(layouttype))) + if (_name != "" && !string.IsNullOrEmpty(_themetype) && (_panelayouts.Count == 0 || !string.IsNullOrEmpty(_layouttype))) { - page = PageState.Pages.Where(item => item.PageId == PageId).FirstOrDefault(); + page = PageState.Pages.FirstOrDefault(item => item.PageId == _pageId); string currentPath = page.Path; - page.Name = name; - if (path == "" && name.ToLower() != "home") + page.Name = _name; + if (_path == "" && _name.ToLower() != "home") { - path = name; + _path = _name; } - if (path.Contains("/")) + if (_path.Contains("/")) { - path = path.Substring(path.LastIndexOf("/") + 1); + _path = _path.Substring(_path.LastIndexOf("/") + 1); } - if (string.IsNullOrEmpty(parentid)) + if (string.IsNullOrEmpty(_parentid)) { page.ParentId = null; - page.Path = Utilities.GetFriendlyUrl(path); + page.Path = Utilities.GetFriendlyUrl(_path); } else { - page.ParentId = Int32.Parse(parentid); + page.ParentId = Int32.Parse(_parentid); Page parent = PageState.Pages.FirstOrDefault(item => item.PageId == page.ParentId); if (parent.Path == "") { - page.Path = Utilities.GetFriendlyUrl(parent.Name) + "/" + Utilities.GetFriendlyUrl(path); + page.Path = Utilities.GetFriendlyUrl(parent.Name) + "/" + Utilities.GetFriendlyUrl(_path); } else { - page.Path = parent.Path + "/" + Utilities.GetFriendlyUrl(path); + page.Path = parent.Path + "/" + Utilities.GetFriendlyUrl(_path); } } - if (insert != "=") + if (_insert != "=") { Page child; - switch (insert) + switch (_insert) { case "<<": page.Order = 0; break; case "<": - child = PageState.Pages.FirstOrDefault(item => item.PageId == childid); + child = PageState.Pages.FirstOrDefault(item => item.PageId == _childid); if (child != null) page.Order = child.Order - 1; break; case ">": - child = PageState.Pages.FirstOrDefault(item => item.PageId == childid); + child = PageState.Pages.FirstOrDefault(item => item.PageId == _childid); if (child != null) page.Order = child.Order + 1; break; case ">>": @@ -360,12 +362,12 @@ break; } } - page.IsNavigation = (isnavigation == null ? true : Boolean.Parse(isnavigation)); - page.EditMode = (mode == "edit" ? true : false); - page.ThemeType = themetype; - page.LayoutType = layouttype ?? ""; - page.Icon = icon ?? ""; - page.Permissions = permissiongrid.GetPermissions(); + page.IsNavigation = (_isnavigation == null || Boolean.Parse(_isnavigation)); + page.EditMode = (_mode == "edit"); + page.ThemeType = _themetype; + page.LayoutType = _layouttype ?? ""; + page.Icon = _icon ?? ""; + page.Permissions = _permissionGrid.GetPermissions(); if (page.ThemeType == PageState.Site.DefaultThemeType) { @@ -375,22 +377,22 @@ { page.LayoutType = ""; } - page.IsPersonalizable = (ispersonalizable != null && Boolean.Parse(ispersonalizable)); + page.IsPersonalizable = (_ispersonalizable != null && Boolean.Parse(_ispersonalizable)); page.UserId = null; page = await PageService.UpdatePageAsync(page); await PageService.UpdatePageOrderAsync(page.SiteId, page.PageId, page.ParentId); - if (currentparentid == "") + if (_currentparentid == "") { await PageService.UpdatePageOrderAsync(page.SiteId, page.PageId, null); } else { - await PageService.UpdatePageOrderAsync(page.SiteId, page.PageId, int.Parse(currentparentid)); + await PageService.UpdatePageOrderAsync(page.SiteId, page.PageId, int.Parse(_currentparentid)); } // update child paths - if (parentid != currentparentid) + if (_parentid != _currentparentid) { foreach (Page p in PageState.Pages.Where(item => item.Path.StartsWith(currentPath))) { diff --git a/Oqtane.Client/Modules/Admin/Site/Index.razor b/Oqtane.Client/Modules/Admin/Site/Index.razor index b3692a49..a6bdcac0 100644 --- a/Oqtane.Client/Modules/Admin/Site/Index.razor +++ b/Oqtane.Client/Modules/Admin/Site/Index.razor @@ -7,7 +7,7 @@ @inject IThemeService ThemeService @inject ISettingService SettingService -@if (themes != null) +@if (_themes != null) { @@ -15,7 +15,7 @@ @@ -23,7 +23,7 @@ @@ -31,7 +31,7 @@ @@ -39,7 +39,7 @@ @@ -49,9 +49,9 @@ @@ -122,7 +122,7 @@ @@ -130,7 +130,7 @@ @@ -138,7 +138,7 @@ @@ -146,7 +146,7 @@
- +
- +
- +
- +
- - @foreach (KeyValuePair panelayout in panelayouts) + @foreach (KeyValuePair panelayout in _panelayouts) { } @@ -82,9 +82,9 @@ - - @foreach (KeyValuePair container in containers) + @foreach (KeyValuePair container in _containers) { } @@ -96,7 +96,7 @@ - @@ -114,7 +114,7 @@ - +
- +
- +
- +
- +
@@ -156,85 +156,85 @@ Cancel

- + } @code { public override SecurityAccessLevel SecurityAccessLevel { get { return SecurityAccessLevel.Admin; } } - Dictionary themes; - Dictionary panelayouts; - Dictionary containers; + Dictionary _themes; + Dictionary _panelayouts; + Dictionary _containers; - List Themes; - string name = ""; - List tenants; - string tenant = ""; - List aliases; - string urls = ""; - int logofileid = -1; - FileManager filemanager; - string themetype; - string layouttype; - string containertype; + List _themeList; + string _name = ""; + List _tenantList; + string _tenant = ""; + List _aliasList; + string _urls = ""; + int _logofileid = -1; + FileManager _filemanager; + string _themetype; + string _layouttype; + string _containertype; - string smtphost = ""; - string smtpport = ""; - string smtpssl = ""; - string smtpusername = ""; - string smtppassword = ""; + string _smtphost = ""; + string _smtpport = ""; + string _smtpssl = ""; + string _smtpusername = ""; + string _smtppassword = ""; - string createdby; - DateTime createdon; - string modifiedby; - DateTime modifiedon; - string deletedby; - DateTime? deletedon; - string isdeleted; + string _createdby; + DateTime _createdon; + string _modifiedby; + DateTime _modifiedon; + string _deletedby; + DateTime? _deletedon; + string _isdeleted; protected override async Task OnInitializedAsync() { try { - Themes = await ThemeService.GetThemesAsync(); - aliases = await AliasService.GetAliasesAsync(); + _themeList = await ThemeService.GetThemesAsync(); + _aliasList = await AliasService.GetAliasesAsync(); Site site = await SiteService.GetSiteAsync(PageState.Site.SiteId, PageState.Alias); if (site != null) { - name = site.Name; - tenants = await TenantService.GetTenantsAsync(); - tenant = tenants.Find(item => item.TenantId == site.TenantId).Name; - foreach (Alias alias in aliases.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList()) + _name = site.Name; + _tenantList = await TenantService.GetTenantsAsync(); + _tenant = _tenantList.Find(item => item.TenantId == site.TenantId).Name; + foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList()) { - urls += alias.Name + "\n"; + _urls += alias.Name + "\n"; } if (site.LogoFileId != null) { - logofileid = site.LogoFileId.Value; + _logofileid = site.LogoFileId.Value; } - themetype = site.DefaultThemeType; - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); - layouttype = site.DefaultLayoutType; - containertype = site.DefaultContainerType; + _themetype = site.DefaultThemeType; + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); + _layouttype = site.DefaultLayoutType; + _containertype = site.DefaultContainerType; Dictionary settings = await SettingService.GetSiteSettingsAsync(site.SiteId); - smtphost = SettingService.GetSetting(settings, "SMTPHost", ""); - smtpport = SettingService.GetSetting(settings, "SMTPPort", ""); - smtpssl = SettingService.GetSetting(settings, "SMTPSSL", ""); - smtpusername = SettingService.GetSetting(settings, "SMTPUsername", ""); - smtppassword = SettingService.GetSetting(settings, "SMTPPassword", ""); + _smtphost = SettingService.GetSetting(settings, "SMTPHost", ""); + _smtpport = SettingService.GetSetting(settings, "SMTPPort", ""); + _smtpssl = SettingService.GetSetting(settings, "SMTPSSL", ""); + _smtpusername = SettingService.GetSetting(settings, "SMTPUsername", ""); + _smtppassword = SettingService.GetSetting(settings, "SMTPPassword", ""); - createdby = site.CreatedBy; - createdon = site.CreatedOn; - modifiedby = site.ModifiedBy; - modifiedon = site.ModifiedOn; - deletedby = site.DeletedBy; - deletedon = site.DeletedOn; - isdeleted = site.IsDeleted.ToString(); + _createdby = site.CreatedBy; + _createdon = site.CreatedOn; + _modifiedby = site.ModifiedBy; + _modifiedon = site.ModifiedOn; + _deletedby = site.DeletedBy; + _deletedon = site.DeletedOn; + _isdeleted = site.IsDeleted.ToString(); } - themes = ThemeService.GetThemeTypes(Themes); - containers = ThemeService.GetContainerTypes(Themes); + _themes = ThemeService.GetThemeTypes(_themeList); + _containers = ThemeService.GetContainerTypes(_themeList); } catch (Exception ex) { @@ -247,20 +247,20 @@ { try { - themetype = (string)e.Value; - if (themetype != "") + _themetype = (string)e.Value; + if (_themetype != "") { - panelayouts = ThemeService.GetPaneLayoutTypes(Themes, themetype); + _panelayouts = ThemeService.GetPaneLayoutTypes(_themeList, _themetype); } else { - panelayouts = new Dictionary(); + _panelayouts = new Dictionary(); } StateHasChanged(); } catch (Exception ex) { - await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", themetype, ex.Message); + await logger.LogError(ex, "Error Loading Pane Layouts For Theme {ThemeType} {Error}", _themetype, ex.Message); AddModuleMessage("Error Loading Pane Layouts For Theme", MessageType.Error); } } @@ -269,12 +269,12 @@ { try { - if (name != "" && urls != "" && !string.IsNullOrEmpty(themetype) && (panelayouts.Count == 0 || !string.IsNullOrEmpty(layouttype)) && !string.IsNullOrEmpty(containertype)) + if (_name != "" && _urls != "" && !string.IsNullOrEmpty(_themetype) && (_panelayouts.Count == 0 || !string.IsNullOrEmpty(_layouttype)) && !string.IsNullOrEmpty(_containertype)) { bool unique = true; - foreach (string name in urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (string name in _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { - if (aliases.Exists(item => item.Name == name && item.SiteId != PageState.Alias.SiteId && item.TenantId != PageState.Alias.TenantId)) + if (_aliasList.Exists(item => item.Name == name && item.SiteId != PageState.Alias.SiteId && item.TenantId != PageState.Alias.TenantId)) { unique = false; } @@ -284,23 +284,23 @@ Site site = await SiteService.GetSiteAsync(PageState.Site.SiteId, PageState.Alias); if (site != null) { - site.Name = name; + site.Name = _name; site.LogoFileId = null; - int logofileid = filemanager.GetFileId(); + int logofileid = _filemanager.GetFileId(); if (logofileid != -1) { site.LogoFileId = logofileid; } - site.DefaultThemeType = themetype; - site.DefaultLayoutType = (layouttype == null ? "" : layouttype); - site.DefaultContainerType = containertype; - site.IsDeleted = (isdeleted == null ? true : Boolean.Parse(isdeleted)); + site.DefaultThemeType = _themetype; + site.DefaultLayoutType = (_layouttype == null ? "" : _layouttype); + site.DefaultContainerType = _containertype; + site.IsDeleted = (_isdeleted == null ? true : Boolean.Parse(_isdeleted)); site = await SiteService.UpdateSiteAsync(site, PageState.Alias); - urls = urls.Replace("\n", ","); - string[] names = urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - foreach (Alias alias in aliases.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList()) + _urls = _urls.Replace("\n", ","); + string[] names = _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList()) { if (!names.Contains(alias.Name)) { @@ -309,7 +309,7 @@ } foreach (string name in names) { - if (!aliases.Exists(item => item.Name == name)) + if (!_aliasList.Exists(item => item.Name == name)) { Alias alias = new Alias(); alias.Name = name; @@ -320,11 +320,11 @@ } Dictionary settings = await SettingService.GetSiteSettingsAsync(site.SiteId); - SettingService.SetSetting(settings, "SMTPHost", smtphost); - SettingService.SetSetting(settings, "SMTPPort", smtpport); - SettingService.SetSetting(settings, "SMTPSSL", smtpssl); - SettingService.SetSetting(settings, "SMTPUsername", smtpusername); - SettingService.SetSetting(settings, "SMTPPassword", smtppassword); + SettingService.SetSetting(settings, "SMTPHost", _smtphost); + SettingService.SetSetting(settings, "SMTPPort", _smtpport); + SettingService.SetSetting(settings, "SMTPSSL", _smtpssl); + SettingService.SetSetting(settings, "SMTPUsername", _smtpusername); + SettingService.SetSetting(settings, "SMTPPassword", _smtppassword); await SettingService.UpdateSiteSettingsAsync(settings, site.SiteId); await logger.LogInformation("Site Saved {Site}", site); diff --git a/Oqtane.Client/Modules/Admin/Sites/Edit.razor b/Oqtane.Client/Modules/Admin/Sites/Edit.razor index bc3b499c..9ff55903 100644 --- a/Oqtane.Client/Modules/Admin/Sites/Edit.razor +++ b/Oqtane.Client/Modules/Admin/Sites/Edit.razor @@ -6,7 +6,7 @@ @inject IAliasService AliasService @inject IThemeService ThemeService -@if (themes != null) +@if (_themes != null) { @@ -14,7 +14,7 @@ @@ -22,7 +22,7 @@ @@ -30,7 +30,7 @@
- +
- +
-