diff --git a/zero.Core/Api/ApplicationsApi.cs b/zero.Core/Api/ApplicationsApi.cs index a3f16323..60634e98 100644 --- a/zero.Core/Api/ApplicationsApi.cs +++ b/zero.Core/Api/ApplicationsApi.cs @@ -3,6 +3,7 @@ using Raven.Client.Documents; using Raven.Client.Documents.Session; using System.Collections.Generic; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; @@ -13,7 +14,7 @@ namespace zero.Core.Api IValidator Validator; - public ApplicationsApi(IBackofficeStore store, IValidator validator) : base(store, isCoreDatabase: true) + public ApplicationsApi(ICollectionContext store, IValidator validator) : base(store, isCoreDatabase: true) { Validator = validator; } @@ -29,8 +30,7 @@ namespace zero.Core.Api /// public async Task> GetAll() { - using IAsyncDocumentSession session = Session(); - return await session + return await Session .Query() .OrderByDescending(x => x.CreatedDate) .ToListAsync(); @@ -42,8 +42,7 @@ namespace zero.Core.Api { query.SearchFor(entity => entity.Name); - using IAsyncDocumentSession session = Session(); - return await session.Query().ToQueriedListAsync(query); + return await Session.Query().ToQueriedListAsync(query); } diff --git a/zero.Core/Api/AuthenticationApi.cs b/zero.Core/Api/AuthenticationApi.cs index bcc7b144..e7f56af7 100644 --- a/zero.Core/Api/AuthenticationApi.cs +++ b/zero.Core/Api/AuthenticationApi.cs @@ -19,14 +19,14 @@ namespace zero.Core.Api protected SignInManager SignInManager { get; private set; } - protected IZeroStore Store { get; set; } + protected IZeroDocumentSession Session { get; set; } - public AuthenticationApi(IZeroContext context, SignInManager signInManager, IZeroStore store) + public AuthenticationApi(IZeroContext context, SignInManager signInManager, IZeroDocumentSession session) { Context = context; SignInManager = signInManager; - Store = store; + Session = session.Core; } @@ -161,9 +161,8 @@ namespace zero.Core.Api //RandomNumberGenerator.Fill(bytes); //user.SecurityStamp = Base32.ToBase32(bytes); // TODO update security stamp but Base32 is .net core internal - using IAsyncDocumentSession session = Store.OpenCoreSession(); - await session.StoreAsync(user); - await session.SaveChangesAsync(); + await Session.StoreAsync(user); + await Session.SaveChangesAsync(); return true; } diff --git a/zero.Core/Api/BackofficeApi.cs b/zero.Core/Api/BackofficeApi.cs index 00e6688e..e8ea13af 100644 --- a/zero.Core/Api/BackofficeApi.cs +++ b/zero.Core/Api/BackofficeApi.cs @@ -4,8 +4,10 @@ using Raven.Client; using Raven.Client.Documents.Session; using System; using System.Collections.Generic; +using System.Security.Claims; using System.Threading.Tasks; using zero.Core.Attributes; +using zero.Core.Collections; using zero.Core.Database; using zero.Core.Entities; using zero.Core.Extensions; @@ -19,35 +21,27 @@ namespace zero.Core.Api const string NEW_ID = "new:"; - protected IBackofficeStore Backoffice { get; private set; } + protected ICollectionContext Context { get; private set; } + + protected IZeroDocumentSession Session { get; private set; } protected bool IsCoreDatabase { get; private set; } - public BackofficeApi(IBackofficeStore store) + public BackofficeApi(ICollectionContext context) { - Store = store.Store; - Backoffice = store; + Context = context; + Store = context.Store; + Session = context.Session; IsCoreDatabase = false; } - internal BackofficeApi(IBackofficeStore store, bool isCoreDatabase) + internal BackofficeApi(ICollectionContext context, bool isCoreDatabase) : this(context) { - Store = store.Store; - Backoffice = store; IsCoreDatabase = isCoreDatabase; - } - - - protected IAsyncDocumentSession Session() - { - if (!IsCoreDatabase) + if (IsCoreDatabase) { - return Store.OpenAsyncSession(); - } - else - { - return Store.OpenAsyncSession(Backoffice.Options.Raven.Database); + Session = Context.Session.Core; } } @@ -60,16 +54,14 @@ namespace zero.Core.Api return default; } - using IAsyncDocumentSession session = Session(); - return await session.LoadAsync(id); + return await Session.LoadAsync(id); } /// public async Task> GetByIds(params string[] ids) where T : ZeroIdEntity { - using IAsyncDocumentSession session = Session(); - Dictionary models = await session.LoadAsync(ids); + Dictionary models = await Session.LoadAsync(ids); Dictionary result = new Dictionary(); foreach (string id in ids) @@ -143,7 +135,7 @@ namespace zero.Core.Api } // get current user - string userId = Backoffice.Auth.GetUserId(); + string userId = Context.Context.BackofficeUser.FindFirstValue(Constants.Auth.Claims.UserId); // set default properties if (model.Id.IsNullOrEmpty()) @@ -160,14 +152,13 @@ namespace zero.Core.Api model.CreatedById ??= userId; model.Hash ??= IdGenerator.Classic(); - using IAsyncDocumentSession session = Session(); - session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); + Session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); - await session.StoreAsync(model); + await Session.StoreAsync(model); - meta?.Invoke(session.Advanced.GetMetadataFor(model)); + meta?.Invoke(Session.Advanced.GetMetadataFor(model)); - await session.SaveChangesAsync(); + await Session.SaveChangesAsync(); return EntityResult.Success(model); } @@ -177,19 +168,18 @@ namespace zero.Core.Api /// public async Task> DeleteById(string id) where T : ZeroIdEntity { - using IAsyncDocumentSession session = Session(); - session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); + Session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); - T entity = await session.LoadAsync(id); + T entity = await Session.LoadAsync(id); if (entity == null) { return EntityResult.Fail("@errors.ondelete.idnotfound"); } - session.Delete(entity); + Session.Delete(entity); - await session.SaveChangesAsync(); + await Session.SaveChangesAsync(); return EntityResult.Success(); } @@ -213,8 +203,7 @@ namespace zero.Core.Api /// public async Task> Purge(string querySuffix = null, Parameters parameters = null) { - string database = IsCoreDatabase ? Backoffice.Options.Raven.Database : null; - await Store.PurgeAsync(database, querySuffix, parameters); + await Store.PurgeAsync(Session.Advanced.DocumentStore.Database, querySuffix, parameters); return EntityResult.Success(); } } diff --git a/zero.Core/Api/MediaApi.cs b/zero.Core/Api/MediaApi.cs index 43c5d093..9ab70395 100644 --- a/zero.Core/Api/MediaApi.cs +++ b/zero.Core/Api/MediaApi.cs @@ -14,6 +14,7 @@ using System.Threading; using zero.Core.Database.Indexes; using Raven.Client.Documents; using Raven.Client.Documents.Linq; +using zero.Core.Collections; namespace zero.Core.Api { @@ -32,7 +33,7 @@ namespace zero.Core.Api protected IPaths Paths { get; set; } - public MediaApi(IBackofficeStore store, IPaths paths) : base(store) + public MediaApi(ICollectionContext store, IPaths paths) : base(store) { Paths = paths; } @@ -48,7 +49,7 @@ namespace zero.Core.Api /// public async Task GetSourceById(string id, bool thumb = false, bool isCoreDatabase = false) { - using IAsyncDocumentSession session = isCoreDatabase ? Store.OpenCoreSession() : Store.OpenAsyncSession(); + IAsyncDocumentSession session = isCoreDatabase ? Session.Core : Session; Media media = await session.LoadAsync(id); @@ -69,10 +70,7 @@ namespace zero.Core.Api /// public async Task> GetById(IEnumerable ids) { - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.LoadAsync(ids); - } + return await Session.LoadAsync(ids); } @@ -81,12 +79,9 @@ namespace zero.Core.Api { query.SearchFor(entity => entity.Name); - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .WhereIf(x => x.FolderId == query.FolderId, !query.FolderId.IsNullOrEmpty(), x => x.FolderId == null) - .ToQueriedListAsync(query); - } + return await Session.Query() + .WhereIf(x => x.FolderId == query.FolderId, !query.FolderId.IsNullOrEmpty(), x => x.FolderId == null) + .ToQueriedListAsync(query); } @@ -102,10 +97,7 @@ namespace zero.Core.Api .OrderByDescending(x => x.IsFolder) .ThenBy(query.OrderBy, query.OrderIsDescending, query.OrderType == ListQueryOrderType.String ? OrderingType.String : OrderingType.Double); - using IAsyncDocumentSession session = Store.OpenAsyncSession(); - session.Advanced.MaxNumberOfRequestsPerSession = query.PageSize + 1; - - IRavenQueryable dbQuery = session.Query().ProjectInto(); + IRavenQueryable dbQuery = Session.Query().ProjectInto(); if (!hasSearch || !query.SearchIsGlobal) { @@ -118,7 +110,7 @@ namespace zero.Core.Api { if (item.IsFolder) { - item.Children = await session.Query().CountAsync(x => x.ParentId == item.Id); + item.Children = await Session.Query().CountAsync(x => x.ParentId == item.Id); } } diff --git a/zero.Core/Api/MediaFolderApi.cs b/zero.Core/Api/MediaFolderApi.cs index 762431e9..df6af9cc 100644 --- a/zero.Core/Api/MediaFolderApi.cs +++ b/zero.Core/Api/MediaFolderApi.cs @@ -5,6 +5,7 @@ using Raven.Client.Documents.Session; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Database.Indexes; using zero.Core.Entities; using zero.Core.Extensions; @@ -17,7 +18,7 @@ namespace zero.Core.Api IValidator Validator; - public MediaFolderApi(IBackofficeStore store, IValidator validator) : base(store) + public MediaFolderApi(ICollectionContext store, IValidator validator) : base(store) { Validator = validator; } @@ -33,13 +34,10 @@ namespace zero.Core.Api /// public async Task> GetAll(string parentId = null) { - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null) - .OrderByDescending(x => x.Name) - .ToListAsync(); - } + return await Session.Query() + .WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null) + .OrderByDescending(x => x.Name) + .ToListAsync(); } @@ -49,63 +47,60 @@ namespace zero.Core.Api List items = new List(); string[] openIds = new string[0] { }; - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) + IList folders = await Session.Query() + .WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null) + .OrderByDescending(x => x.CreatedDate).ThenBy(x => x.Name) + .ToListAsync(); + + + // get hierarchy so we know if we should set the folder to open + if (!activeId.IsNullOrEmpty()) { - IList folders = await session.Query() - .WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null) - .OrderByDescending(x => x.CreatedDate).ThenBy(x => x.Name) - .ToListAsync(); + MediaFolder_ByHierarchy.Result result = await Session.Query() + .ProjectInto() + .Include(x => x.Path.Select(p => p.Id)) + .FirstOrDefaultAsync(x => x.Id == activeId); - - // get hierarchy so we know if we should set the folder to open - if (!activeId.IsNullOrEmpty()) + if (result != null) { - MediaFolder_ByHierarchy.Result result = await session.Query() - .ProjectInto() - .Include(x => x.Path.Select(p => p.Id)) - .FirstOrDefaultAsync(x => x.Id == activeId); - - if (result != null) - { - openIds = result.Path.Select(x => x.Id).ToArray(); - } + openIds = result.Path.Select(x => x.Id).ToArray(); } - - - // get children for all folders - string[] folderIds = folders.Select(x => x.Id).ToArray(); - - IList children = await session.Query() - .ProjectInto() - .Where(x => x.Id.In(folderIds)) - .ToListAsync(); - - - foreach (MediaFolder folder in folders) - { - int childCount = children.Count(x => x.Id == folder.Id); - - items.Add(new TreeItem() - { - Id = folder.Id, - Name = folder.Name, - HasChildren = childCount > 0, - ChildCount = childCount, - ParentId = folder.ParentId, - Sort = folder.Sort, - Icon = "fth-folder", - IsOpen = openIds.Contains(folder.Id), - IsInactive = !folder.IsActive, - HasActions = true, - Modifier = !folder.IsActive ? new TreeItemModifier() - { - Icon = "fth-minus-circle color-yellow", - Name = "Inactive" - } : null - }); - } } + + // get children for all folders + string[] folderIds = folders.Select(x => x.Id).ToArray(); + + IList children = await Session.Query() + .ProjectInto() + .Where(x => x.Id.In(folderIds)) + .ToListAsync(); + + + foreach (MediaFolder folder in folders) + { + int childCount = children.Count(x => x.Id == folder.Id); + + items.Add(new TreeItem() + { + Id = folder.Id, + Name = folder.Name, + HasChildren = childCount > 0, + ChildCount = childCount, + ParentId = folder.ParentId, + Sort = folder.Sort, + Icon = "fth-folder", + IsOpen = openIds.Contains(folder.Id), + IsInactive = !folder.IsActive, + HasActions = true, + Modifier = !folder.IsActive ? new TreeItemModifier() + { + Icon = "fth-minus-circle color-yellow", + Name = "Inactive" + } : null + }); + } + //if (parentId.IsNullOrEmpty()) //{ // items.Add(new TreeItem() @@ -126,23 +121,20 @@ namespace zero.Core.Api /// public async Task> GetHierarchy(string id) { - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) + MediaFolder_ByHierarchy.Result result = await Session.Query() + .ProjectInto() + .Include(x => x.Path.Select(p => p.Id)) + .FirstOrDefaultAsync(x => x.Id == id); + + if (result == null) { - MediaFolder_ByHierarchy.Result result = await session.Query() - .ProjectInto() - .Include(x => x.Path.Select(p => p.Id)) - .FirstOrDefaultAsync(x => x.Id == id); - - if (result == null) - { - return new List(); - } - - List ids = result.Path.Select(x => x.Id).ToList(); - ids.Add(id); - - return (await session.LoadAsync(ids)).Select(x => x.Value).ToList(); + return new List(); } + + List ids = result.Path.Select(x => x.Id).ToList(); + ids.Add(id); + + return (await Session.LoadAsync(ids)).Select(x => x.Value).ToList(); } diff --git a/zero.Core/Api/ModulesApi.cs b/zero.Core/Api/ModulesApi.cs index 8a37f920..150bfac1 100644 --- a/zero.Core/Api/ModulesApi.cs +++ b/zero.Core/Api/ModulesApi.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; using zero.Core.Handlers; @@ -15,7 +16,7 @@ namespace zero.Core.Api protected IHandlerHolder Handler { get; private set; } - public ModulesApi(IZeroOptions options, IBackofficeStore store, IHandlerHolder handler) : base(store) + public ModulesApi(IZeroOptions options, ICollectionContext store, IHandlerHolder handler) : base(store) { Options = options; Handler = handler; @@ -47,7 +48,7 @@ namespace zero.Core.Api return modules; } - return handler.GetAllowedModuleTypes(Backoffice.Context.Application, types, page, tags)?.ToList() ?? new(); + return handler.GetAllowedModuleTypes(Context.Context.Application, types, page, tags)?.ToList() ?? new(); } diff --git a/zero.Core/Api/PageTreeApi.cs b/zero.Core/Api/PageTreeApi.cs index ab48ddda..01c57f41 100644 --- a/zero.Core/Api/PageTreeApi.cs +++ b/zero.Core/Api/PageTreeApi.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Database.Indexes; using zero.Core.Entities; using zero.Core.Extensions; @@ -17,7 +18,7 @@ namespace zero.Core.Api { protected IRoutes Routes { get; set; } - public PageTreeApi(IBackofficeStore store, IRoutes routes) : base(store) + public PageTreeApi(ICollectionContext store, IRoutes routes) : base(store) { Routes = routes; } @@ -27,18 +28,15 @@ namespace zero.Core.Api public async Task> GetChildren(string parentId = null, string activeId = null, string search = null) { IList items = new List(); - IReadOnlyCollection pageTypes = Backoffice.Options.Pages.GetAllItems(); + IReadOnlyCollection pageTypes = Context.Options.Pages.GetAllItems(); string[] openIds = new string[0] { }; IList pages = null; IList children = null; bool isSearch = !search.IsNullOrWhiteSpace(); - using IAsyncDocumentSession session = Store.OpenAsyncSession(); - - if (isSearch) { - pages = await session + pages = await Session .Query() .SearchIf(x => x.Name, search, "*") .OrderBy(x => x.Sort, OrderingType.Long) @@ -57,7 +55,7 @@ namespace zero.Core.Api else { - pages = await session + pages = await Session .Query() .WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null) .OrderBy(x => x.Sort, OrderingType.Long) @@ -67,7 +65,7 @@ namespace zero.Core.Api // get hierarchy so we know if we should set the page to open if (!activeId.IsNullOrEmpty()) { - Pages_ByHierarchy.Result result = await session.Query() + Pages_ByHierarchy.Result result = await Session.Query() .ProjectInto() .Include(x => x.Path.Select(p => p.Id)) .FirstOrDefaultAsync(x => x.Id == activeId); @@ -82,7 +80,7 @@ namespace zero.Core.Api // get children for all pages string[] pageIds = pages.Select(x => x.Id).ToArray(); - children = await session.Query() + children = await Session.Query() .ProjectInto() .Where(x => x.Id.In(pageIds)) .ToListAsync(); diff --git a/zero.Core/Api/PreviewApi.cs b/zero.Core/Api/PreviewApi.cs index b48a5017..37d6ed6a 100644 --- a/zero.Core/Api/PreviewApi.cs +++ b/zero.Core/Api/PreviewApi.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; using Rc = Raven.Client; @@ -10,7 +11,7 @@ namespace zero.Core.Api { Preview Blueprint; - public PreviewApi(IBackofficeStore store, Preview blueprint) : base(store) + public PreviewApi(ICollectionContext store, Preview blueprint) : base(store) { Blueprint = blueprint; } diff --git a/zero.Core/Api/RecycleBinApi.cs b/zero.Core/Api/RecycleBinApi.cs index 90784579..2b723888 100644 --- a/zero.Core/Api/RecycleBinApi.cs +++ b/zero.Core/Api/RecycleBinApi.cs @@ -3,6 +3,7 @@ using Raven.Client.Documents.Linq; using Raven.Client.Documents.Session; using System.Collections.Generic; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; using zero.Core.Utils; @@ -13,7 +14,7 @@ namespace zero.Core.Api { RecycledEntity Blueprint; - public RecycleBinApi(IBackofficeStore store, RecycledEntity blueprint) : base(store) + public RecycleBinApi(ICollectionContext store, RecycledEntity blueprint) : base(store) { Blueprint = blueprint; } @@ -67,25 +68,19 @@ namespace zero.Core.Api { query.SearchSelector = x => x.Name; - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .WhereIf(x => x.Group == query.Group, !query.Group.IsNullOrWhiteSpace()) - .WhereIf(x => x.OperationId == query.OperationId, !query.OperationId.IsNullOrWhiteSpace()) - .ToQueriedListAsync(query); - } + return await Session.Query() + .WhereIf(x => x.Group == query.Group, !query.Group.IsNullOrWhiteSpace()) + .WhereIf(x => x.OperationId == query.OperationId, !query.OperationId.IsNullOrWhiteSpace()) + .ToQueriedListAsync(query); } /// public async Task> GetByOperation(string operationId) { - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.OperationId == operationId) - .ToListAsync(); - } + return await Session.Query() + .Where(x => x.OperationId == operationId) + .ToListAsync(); } @@ -94,12 +89,9 @@ namespace zero.Core.Api /// public async Task GetCountByOperation(string operationId) { - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.OperationId == operationId) - .CountAsync(); - } + return await Session.Query() + .Where(x => x.OperationId == operationId) + .CountAsync(); } diff --git a/zero.Core/Api/SpacesApi.cs b/zero.Core/Api/SpacesApi.cs index 4298fce9..8039b915 100644 --- a/zero.Core/Api/SpacesApi.cs +++ b/zero.Core/Api/SpacesApi.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; @@ -15,7 +16,7 @@ namespace zero.Core.Api protected IPermissionsApi PermissionsApi { get; private set; } - public SpacesApi(IBackofficeStore store, IPermissionsApi permissionsApi) : base(store) + public SpacesApi(ICollectionContext store, IPermissionsApi permissionsApi) : base(store) { PermissionsApi = permissionsApi; } @@ -39,7 +40,7 @@ namespace zero.Core.Api /// public IReadOnlyCollection GetAll() { - return Backoffice.Options.Spaces.GetAllItems(); + return Context.Options.Spaces.GetAllItems(); } @@ -47,14 +48,10 @@ namespace zero.Core.Api public async Task GetItem(string alias, string id = null) { Space space = GetByAlias(alias); - - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.SpaceAlias == space.Alias) - .WhereIf(x => x.Id == id, !id.IsNullOrEmpty()) - .FirstOrDefaultAsync(); - } + return await Session.Query() + .Where(x => x.SpaceAlias == space.Alias) + .WhereIf(x => x.Id == id, !id.IsNullOrEmpty()) + .FirstOrDefaultAsync(); } @@ -63,13 +60,10 @@ namespace zero.Core.Api { Space space = GetBy(); - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.SpaceAlias == space.Alias) - .WhereIf(x => x.Id == id, !id.IsNullOrEmpty()) - .FirstOrDefaultAsync(); - } + return await Session.Query() + .Where(x => x.SpaceAlias == space.Alias) + .WhereIf(x => x.Id == id, !id.IsNullOrEmpty()) + .FirstOrDefaultAsync(); } @@ -78,21 +72,18 @@ namespace zero.Core.Api { Space space = GetBy(); - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) + ids = ids.Distinct().ToArray(); + + Dictionary models = await Session.LoadAsync(ids); + Dictionary result = new Dictionary(); + + foreach (string id in ids) { - ids = ids.Distinct().ToArray(); - - Dictionary models = await session.LoadAsync(ids); - Dictionary result = new Dictionary(); - - foreach (string id in ids) - { - models.TryGetValue(id, out T model); - result.Add(id, model); - } - - return result; + models.TryGetValue(id, out T model); + result.Add(id, model); } + + return result; } @@ -101,12 +92,9 @@ namespace zero.Core.Api { query.SearchSelector = item => item.Name; - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.SpaceAlias == alias) - .ToQueriedListAsync(query); - } + return await Session.Query() + .Where(x => x.SpaceAlias == alias) + .ToQueriedListAsync(query); } @@ -115,12 +103,9 @@ namespace zero.Core.Api { query.SearchSelector = item => item.Name; - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.SpaceAlias == alias) - .ToQueriedListAsync(query); - } + return await Session.Query() + .Where(x => x.SpaceAlias == alias) + .ToQueriedListAsync(query); } @@ -130,12 +115,9 @@ namespace zero.Core.Api Space space = GetBy(); query.SearchSelector = item => item.Name; - using (IAsyncDocumentSession session = Store.OpenAsyncSession()) - { - return await session.Query() - .Where(x => x.SpaceAlias == space.Alias) - .ToQueriedListAsync(query); - } + return await Session.Query() + .Where(x => x.SpaceAlias == space.Alias) + .ToQueriedListAsync(query); } diff --git a/zero.Core/Api/Token.cs b/zero.Core/Api/Token.cs index 210372a3..5b8797b3 100644 --- a/zero.Core/Api/Token.cs +++ b/zero.Core/Api/Token.cs @@ -1,111 +1,111 @@ -using Raven.Client.Documents; -using Raven.Client.Documents.Session; -using System; -using System.Linq; -using System.Threading.Tasks; -using zero.Core.Database; -using zero.Core.Entities; -using zero.Core.Extensions; -using zero.Core.Options; +//using Raven.Client.Documents; +//using Raven.Client.Documents.Session; +//using System; +//using System.Linq; +//using System.Threading.Tasks; +//using zero.Core.Database; +//using zero.Core.Entities; +//using zero.Core.Extensions; +//using zero.Core.Options; -namespace zero.Core.Api -{ - public class Token : IToken - { - protected IZeroStore Store { get; private set; } +//namespace zero.Core.Api +//{ +// public class Token : IToken +// { +// protected IZeroStore Store { get; private set; } - protected IZeroOptions Options { get; private set; } +// protected IZeroOptions Options { get; private set; } - private const string PREFIX = "changeTokens"; +// private const string PREFIX = "changeTokens"; - public Token(IZeroStore store, IZeroOptions options) - { - Store = store; - Options = options; - } +// public Token(IZeroStore store, IZeroOptions options) +// { +// Store = store; +// Options = options; +// } - /// - public bool Verify(ZeroIdEntity entity, string token) - { - return Verify(entity?.Id, token); - } +// /// +// public bool Verify(ZeroIdEntity entity, string token) +// { +// return Verify(entity?.Id, token); +// } - /// - public bool Verify(string entityId, string token) - { - if (token.IsNullOrWhiteSpace() && entityId.IsNullOrEmpty()) - { - return true; - } +// /// +// public bool Verify(string entityId, string token) +// { +// if (token.IsNullOrWhiteSpace() && entityId.IsNullOrEmpty()) +// { +// return true; +// } - if (token.IsNullOrWhiteSpace() || entityId.IsNullOrEmpty()) - { - return false; - } +// if (token.IsNullOrWhiteSpace() || entityId.IsNullOrEmpty()) +// { +// return false; +// } - using (IDocumentSession session = Store.OpenSession()) - { - return session.Query().Any(x => x.Id == token && x.ReferenceId == entityId); - } - } +// using (IDocumentSession session = Store.OpenSession()) +// { +// return session.Query().Any(x => x.Id == token && x.ReferenceId == entityId); +// } +// } - /// - public string Get(ZeroIdEntity entity) - { - return Get(entity?.Id); - } +// /// +// public string Get(ZeroIdEntity entity) +// { +// return Get(entity?.Id); +// } - /// - public string Get(string entityId) - { - if (entityId.IsNullOrEmpty()) - { - return null; - } +// /// +// public string Get(string entityId) +// { +// if (entityId.IsNullOrEmpty()) +// { +// return null; +// } - ChangeToken token = new ChangeToken() - { - Id = Options.Raven.CollectionPrefix.EnsureEndsWith(Store.Raven.Conventions.IdentityPartsSeparator) + PREFIX.EnsureEndsWith(Store.Raven.Conventions.IdentityPartsSeparator) + Guid.NewGuid(), - ReferenceId = entityId - }; +// ChangeToken token = new ChangeToken() +// { +// Id = Options.Raven.CollectionPrefix.EnsureEndsWith(Store.Raven.Conventions.IdentityPartsSeparator) + PREFIX.EnsureEndsWith(Store.Raven.Conventions.IdentityPartsSeparator) + Guid.NewGuid(), +// ReferenceId = entityId +// }; - using (IDocumentSession session = Store.OpenSession()) - { - session.Store(token); - session.Advanced.GetMetadataFor(token)[Constants.Database.Expires] = DateTime.UtcNow.AddMinutes(Options.TokenExpiration); - session.SaveChanges(); - } +// using (IDocumentSession session = Store.OpenSession()) +// { +// session.Store(token); +// session.Advanced.GetMetadataFor(token)[Constants.Database.Expires] = DateTime.UtcNow.AddMinutes(Options.TokenExpiration); +// session.SaveChanges(); +// } - return token.Id; - } - } +// return token.Id; +// } +// } - public interface IToken - { - /// - /// Verifies if the change token is valid for the entity - /// - bool Verify(ZeroIdEntity entity, string token); +// public interface IToken +// { +// /// +// /// Verifies if the change token is valid for the entity +// /// +// bool Verify(ZeroIdEntity entity, string token); - /// - /// Verifies if the change token is valid for the entity - /// - bool Verify(string entityId, string token); +// /// +// /// Verifies if the change token is valid for the entity +// /// +// bool Verify(string entityId, string token); - /// - /// Get a new change token for the entity - /// - string Get(ZeroIdEntity entity); +// /// +// /// Get a new change token for the entity +// /// +// string Get(ZeroIdEntity entity); - /// - /// Get a new change token for the entity - /// - string Get(string entityId); - } -} +// /// +// /// Get a new change token for the entity +// /// +// string Get(string entityId); +// } +//} diff --git a/zero.Core/Api/UserApi.cs b/zero.Core/Api/UserApi.cs index 918c5991..f8cee7f5 100644 --- a/zero.Core/Api/UserApi.cs +++ b/zero.Core/Api/UserApi.cs @@ -5,6 +5,7 @@ using Raven.Client.Documents.Session; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; @@ -14,12 +15,9 @@ namespace zero.Core.Api { protected UserManager UserManager { get; private set; } - protected IZeroContext Context { get; set; } - - public UserApi(IBackofficeStore store, UserManager userManager, IZeroContext context) : base(store, isCoreDatabase: true) + public UserApi(ICollectionContext store, UserManager userManager) : base(store, isCoreDatabase: true) { UserManager = userManager; - Context = context; } @@ -49,8 +47,7 @@ namespace zero.Core.Api /// public async Task> GetAll() { - using IAsyncDocumentSession session = Session(); - return await session.Query() + return await Session.Query() .OrderByDescending(x => x.CreatedDate) .ToListAsync(); } @@ -59,12 +56,11 @@ namespace zero.Core.Api /// public async Task> GetByQuery(ListQuery query) { - string currentUserId = UserManager.GetUserId(Context.BackofficeUser); + string currentUserId = UserManager.GetUserId(Context.Context.BackofficeUser); query.SearchSelector = user => user.Name; - using IAsyncDocumentSession session = Session(); - return await session.Query() + return await Session.Query() .ToQueriedListAsync(query); } diff --git a/zero.Core/Api/UserRolesApi.cs b/zero.Core/Api/UserRolesApi.cs index 56d2afce..8a6c6317 100644 --- a/zero.Core/Api/UserRolesApi.cs +++ b/zero.Core/Api/UserRolesApi.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; +using zero.Core.Collections; using zero.Core.Entities; using zero.Core.Extensions; using zero.Core.Identity; @@ -26,7 +27,7 @@ namespace zero.Core.Api private ClaimsPrincipal Principal => HttpContextAccessor.HttpContext?.User; - public UserRolesApi(IHttpContextAccessor httpContextAccessor, UserManager userManager, RoleManager roleManager, IBackofficeStore store) : base(store, isCoreDatabase: true) + public UserRolesApi(IHttpContextAccessor httpContextAccessor, UserManager userManager, RoleManager roleManager, ICollectionContext store) : base(store, isCoreDatabase: true) { HttpContextAccessor = httpContextAccessor; UserManager = userManager; @@ -37,8 +38,7 @@ namespace zero.Core.Api /// public async Task> GetAll() { - using IAsyncDocumentSession session = Session(); - return await session.Query().OrderBy(x => x.Sort).ThenBy(x => x.Name).ToListAsync(); + return await Session.Query().OrderBy(x => x.Sort).ThenBy(x => x.Name).ToListAsync(); } @@ -66,18 +66,15 @@ namespace zero.Core.Api model.Alias = Safenames.Alias(model.Name); - using (IAsyncDocumentSession session = Session()) + await Session.StoreAsync(model); + + string id = Session.Advanced.GetDocumentId(model); + + await Session.SaveChangesAsync(); + + if (model.Id.IsNullOrEmpty()) { - await session.StoreAsync(model); - - string id = session.Advanced.GetDocumentId(model); - - await session.SaveChangesAsync(); - - if (model.Id.IsNullOrEmpty()) - { - model.Id = id; - } + model.Id = id; } return EntityResult.Success(model); @@ -87,20 +84,17 @@ namespace zero.Core.Api /// public async Task> Delete(string id) { - using (IAsyncDocumentSession session = Session()) + BackofficeUserRole country = await Session.LoadAsync(id); + + if (country == null) { - BackofficeUserRole country = await session.LoadAsync(id); - - if (country == null) - { - return EntityResult.Fail("@errors.ondelete.idnotfound"); - } - - session.Delete(country); - - await session.SaveChangesAsync(); + return EntityResult.Fail("@errors.ondelete.idnotfound"); } + Session.Delete(country); + + await Session.SaveChangesAsync(); + return EntityResult.Success(); } } diff --git a/zero.Core/Collections/CollectionBase.cs b/zero.Core/Collections/CollectionBase.cs index 85d7bd5c..5da526bd 100644 --- a/zero.Core/Collections/CollectionBase.cs +++ b/zero.Core/Collections/CollectionBase.cs @@ -9,7 +9,6 @@ using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using zero.Core.Api; -using zero.Core.Attributes; using zero.Core.Database; using zero.Core.Entities; using zero.Core.Extensions; @@ -19,22 +18,24 @@ namespace zero.Core.Collections { public abstract class CollectionBase : ICollectionBase, ICollectionBase, IDisposable where T : ZeroEntity { - private IAsyncDocumentSession _session; private IRevisionsApi _revisions; private string _database; protected ICollectionInterceptorHandler InterceptorHandler { get; private set; } + private IZeroDocumentSession zeroSession; + protected virtual Action PreSave { get; set; } protected bool OnlyActive { get; set; } = false; // TODO do we really need this? - public CollectionBase(IZeroContext context, ICollectionInterceptorHandler interceptorHandler = null, IValidator validator = null) + public CollectionBase(ICollectionContext collectionContext, IValidator validator = null) { - Context = context; - Store = context.Store; - InterceptorHandler = interceptorHandler; + Context = collectionContext.Context; + Store = collectionContext.Store; + InterceptorHandler = collectionContext.InterceptorHandler; + zeroSession = collectionContext.Session; Validator = validator; Database = Store.ResolvedDatabase; } @@ -75,19 +76,7 @@ namespace zero.Core.Collections /// /// Create an an async document session /// - public IAsyncDocumentSession Session - { - get - { - if (_session != null) - { - return _session; - } - _session = Context.GetCurrentScopeAsyncSession(Database ?? Store.ResolvedDatabase); - _session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); - return _session; - } - } + public IZeroDocumentSession Session => Database == Context.Options.Raven.Database ? zeroSession.Core : zeroSession; /// public string Database @@ -97,7 +86,6 @@ namespace zero.Core.Collections { if (value != _database) { - _session = null; _database = value; } } @@ -489,7 +477,7 @@ namespace zero.Core.Collections /// /// Create an async document session /// - IAsyncDocumentSession Session { get; } + IZeroDocumentSession Session { get; } /// /// Applies the scope to the service instance diff --git a/zero.Core/Collections/CollectionContext.cs b/zero.Core/Collections/CollectionContext.cs new file mode 100644 index 00000000..5e9befdd --- /dev/null +++ b/zero.Core/Collections/CollectionContext.cs @@ -0,0 +1,43 @@ +using zero.Core.Collections; +using zero.Core.Database; +using zero.Core.Options; + +namespace zero.Core.Collections +{ + public class CollectionContext : ICollectionContext + { + public IZeroStore Store { get; private set; } + + public IZeroContext Context { get; private set; } + + public IZeroOptions Options { get; private set; } + + public IZeroDocumentSession Session { get; private set; } + + public ICollectionInterceptorHandler InterceptorHandler { get; private set; } + + + public CollectionContext(IZeroStore store, IZeroContext context, IZeroDocumentSession session, IZeroOptions options, ICollectionInterceptorHandler interceptorHandler) + { + Store = store; + Context = context; + Session = session; + Options = options; + InterceptorHandler = interceptorHandler; + } + } + + + public interface ICollectionContext + { + IZeroStore Store { get; } + + IZeroContext Context { get; } + + IZeroOptions Options { get; } + + IZeroDocumentSession Session { get; } + + ICollectionInterceptorHandler InterceptorHandler { get; } + } +} \ No newline at end of file diff --git a/zero.Core/Collections/Countries/CountriesCollection.cs b/zero.Core/Collections/Countries/CountriesCollection.cs index 7b6f9b38..a03e5f55 100644 --- a/zero.Core/Collections/Countries/CountriesCollection.cs +++ b/zero.Core/Collections/Countries/CountriesCollection.cs @@ -9,7 +9,7 @@ namespace zero.Core.Collections { public class CountriesCollection : CollectionBase, ICountriesCollection { - public CountriesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator validator) : base(context, interceptor, validator) { } + public CountriesCollection(ICollectionContext context, IValidator validator) : base(context, validator) { } /// diff --git a/zero.Core/Collections/Integrations/IntegrationsCollection.cs b/zero.Core/Collections/Integrations/IntegrationsCollection.cs index 66840592..f52c06f7 100644 --- a/zero.Core/Collections/Integrations/IntegrationsCollection.cs +++ b/zero.Core/Collections/Integrations/IntegrationsCollection.cs @@ -22,7 +22,7 @@ namespace zero.Core.Collections protected ILogger Logger { get; private set; } - public IntegrationsCollection(IZeroContext context, IZeroOptions options, ILogger logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, interceptorHandler) + public IntegrationsCollection(ICollectionContext context, IZeroOptions options, ILogger logger) : base(context) { Options = options; RegisteredTypes = Options.Integrations.GetAllItems(); diff --git a/zero.Core/Collections/Languages/LanguagesCollection.cs b/zero.Core/Collections/Languages/LanguagesCollection.cs index 2b550842..26e5aaee 100644 --- a/zero.Core/Collections/Languages/LanguagesCollection.cs +++ b/zero.Core/Collections/Languages/LanguagesCollection.cs @@ -12,7 +12,7 @@ namespace zero.Core.Collections { public class LanguagesCollection : CollectionBase, ILanguagesCollection { - public LanguagesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator validator) : base(context, interceptor, validator) { } + public LanguagesCollection(ICollectionContext context, IValidator validator) : base(context, validator) { } /// diff --git a/zero.Core/Collections/MailTemplates/MailTemplatesCollection.cs b/zero.Core/Collections/MailTemplates/MailTemplatesCollection.cs index 39fb20f5..e72482a2 100644 --- a/zero.Core/Collections/MailTemplates/MailTemplatesCollection.cs +++ b/zero.Core/Collections/MailTemplates/MailTemplatesCollection.cs @@ -7,7 +7,7 @@ namespace zero.Core.Collections { public class MailTemplatesCollection : CollectionBase, IMailTemplatesCollection { - public MailTemplatesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator validator) : base(context, interceptor, validator) { } + public MailTemplatesCollection(ICollectionContext context, IValidator validator) : base(context, validator) { } /// diff --git a/zero.Core/Collections/Media/MediaCollection.cs b/zero.Core/Collections/Media/MediaCollection.cs index 77e26497..bf595ccf 100644 --- a/zero.Core/Collections/Media/MediaCollection.cs +++ b/zero.Core/Collections/Media/MediaCollection.cs @@ -21,34 +21,13 @@ namespace zero.Core.Collections { public class MediaCollection : CollectionBase, IMediaCollection { - private IAsyncDocumentSession _coreSession; - - - public MediaCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator validator, IPaths paths) : base(context, interceptor, validator) + public MediaCollection(ICollectionContext context, IValidator validator, IPaths paths) : base(context, validator) { PreSave = model => model.IsActive = true; Paths = paths; } - /// - /// Create an an async document session - /// - protected IAsyncDocumentSession CoreSession - { - get - { - if (_coreSession != null) - { - return _coreSession; - } - _coreSession = Store.OpenCoreSession(); - _coreSession.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false); - return _coreSession; - } - } - - protected const char PATH_SEPARATOR = '/'; protected const string PATH_PREFIX = "/uploads"; @@ -88,7 +67,7 @@ namespace zero.Core.Collections } if (coreIds.Length > 0) { - models = await CoreSession.LoadAsync(coreIds); + models = await Session.Core.LoadAsync(coreIds); foreach (string id in coreIds) { models.TryGetValue(id, out Media model); diff --git a/zero.Core/Collections/Pages/PagesCollection.cs b/zero.Core/Collections/Pages/PagesCollection.cs index 5ae28f3e..90e79f98 100644 --- a/zero.Core/Collections/Pages/PagesCollection.cs +++ b/zero.Core/Collections/Pages/PagesCollection.cs @@ -25,8 +25,8 @@ namespace zero.Core.Collections protected IHandlerHolder Handler { get; private set; } - public PagesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IRecycleBinApi recycleBinApi, IHandlerHolder handler, - ILogger logger, IValidator validator = null) : base(context, interceptor, validator) + public PagesCollection(ICollectionContext context, IRecycleBinApi recycleBinApi, IHandlerHolder handler, + ILogger logger, IValidator validator = null) : base(context, validator) { RecycleBinApi = recycleBinApi; Handler = handler; diff --git a/zero.Core/Collections/Translations/TranslationsCollection.cs b/zero.Core/Collections/Translations/TranslationsCollection.cs index f1594947..a461a49f 100644 --- a/zero.Core/Collections/Translations/TranslationsCollection.cs +++ b/zero.Core/Collections/Translations/TranslationsCollection.cs @@ -9,7 +9,7 @@ namespace zero.Core.Collections { public class TranslationsCollection : CollectionBase, ITranslationsCollection { - public TranslationsCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator validator) : base(context, interceptor, validator) { } + public TranslationsCollection(ICollectionContext context, IValidator validator) : base(context, validator) { } /// diff --git a/zero.Core/Cultures/CultureResolver.cs b/zero.Core/Cultures/CultureResolver.cs index 3d1b42aa..cc0c048d 100644 --- a/zero.Core/Cultures/CultureResolver.cs +++ b/zero.Core/Cultures/CultureResolver.cs @@ -1,9 +1,11 @@ using FluentValidation; using Microsoft.Extensions.Logging; using Raven.Client.Documents; +using Raven.Client.Documents.Session; using System; using System.Globalization; using System.Threading.Tasks; +using zero.Core.Database; using zero.Core.Entities; using zero.Core.Extensions; @@ -31,7 +33,8 @@ namespace zero.Core.Cultures } else { - Language language = await context.GetCurrentScopeAsyncSession().Query().FirstOrDefaultAsync(); + using IAsyncDocumentSession session = context.Store.OpenAsyncSession(); + Language language = await session.Query().FirstOrDefaultAsync(); if (language == null) { diff --git a/zero.Core/Database/ZeroDocumentSession.cs b/zero.Core/Database/ZeroDocumentSession.cs index 2b1b9375..8899085e 100644 --- a/zero.Core/Database/ZeroDocumentSession.cs +++ b/zero.Core/Database/ZeroDocumentSession.cs @@ -1,25 +1,38 @@ using Raven.Client.Documents; using Raven.Client.Documents.Session; using System; +using zero.Core.Extensions; namespace zero.Core.Database { - public class ZeroDocumentSession : AsyncDocumentSession, IZeroDocumentSession, IZeroCoreDocumentSession + public class ZeroDocumentSession : AsyncDocumentSession, IZeroDocumentSession { - public ZeroDocumentSession(DocumentStore documentStore, Guid id, SessionOptions options) : base(documentStore, id, options) - { + public IZeroDocumentSession Core { get; private set; } + public ZeroDocumentSession(DocumentStore documentStore, Guid id, SessionOptions options, string coreDatabase = null) : base(documentStore, id, options) + { + if (coreDatabase.HasValue()) + { + Core = new ZeroDocumentSession(documentStore, id, new SessionOptions() + { + Database = coreDatabase, + DisableAtomicDocumentWritesInClusterWideTransaction = options.DisableAtomicDocumentWritesInClusterWideTransaction, + NoCaching = options.NoCaching, + NoTracking = options.NoTracking, + RequestExecutor = options.RequestExecutor, + TransactionMode = options.TransactionMode + }); + } + else + { + Core = this; + } } } public interface IZeroDocumentSession : IAsyncDocumentSession { - - } - - public interface IZeroCoreDocumentSession : IZeroDocumentSession - { - + IZeroDocumentSession Core { get; } } } diff --git a/zero.Core/Database/ZeroStore.cs b/zero.Core/Database/ZeroStore.cs index 7c2b2bba..9a9bc439 100644 --- a/zero.Core/Database/ZeroStore.cs +++ b/zero.Core/Database/ZeroStore.cs @@ -59,7 +59,7 @@ namespace zero.Core.Database EnsureNotClosed(); var sessionId = Guid.NewGuid(); - var session = new ZeroDocumentSession(this, sessionId, options); + var session = new ZeroDocumentSession(this, sessionId, options, Options.Raven.Database); RegisterEvents(session); AfterSessionCreated(session); diff --git a/zero.Core/Identity/RavenScopedStores.cs b/zero.Core/Identity/RavenScopedStores.cs index 64c9c558..4363b49d 100644 --- a/zero.Core/Identity/RavenScopedStores.cs +++ b/zero.Core/Identity/RavenScopedStores.cs @@ -8,7 +8,7 @@ namespace zero.Core.Identity public class RavenCoreRoleStore : RavenRoleStore where TRole : ZeroIdentityRole { - public RavenCoreRoleStore(IZeroStore store, IZeroOptions options, IZeroCoreDocumentSession coreSession, IdentityErrorDescriber describer = null) : base(store, options, coreSession, describer) { } + public RavenCoreRoleStore(IZeroStore store, IZeroOptions options, IZeroDocumentSession session, IdentityErrorDescriber describer = null) : base(store, options, session.Core, describer) { } } @@ -16,7 +16,7 @@ namespace zero.Core.Identity public class RavenCoreUserStore : RavenUserStore where TUser : ZeroIdentityUser { - public RavenCoreUserStore(IZeroStore store, IZeroOptions options, IZeroCoreDocumentSession coreSession) : base(store, options, coreSession) { } + public RavenCoreUserStore(IZeroStore store, IZeroOptions options, IZeroDocumentSession session) : base(store, options, session.Core) { } } @@ -25,7 +25,7 @@ namespace zero.Core.Identity where TUser : ZeroIdentityUser where TRole : ZeroIdentityRole { - public RavenCoreUserStore(IZeroStore store, IZeroOptions options, IZeroCoreDocumentSession coreSession) : base(store, options, coreSession) { } + public RavenCoreUserStore(IZeroStore store, IZeroOptions options, IZeroDocumentSession session) : base(store, options, session.Core) { } } } diff --git a/zero.Core/Integrations/IntegrationService.cs b/zero.Core/Integrations/IntegrationService.cs index ffb952b6..7cee1d1b 100644 --- a/zero.Core/Integrations/IntegrationService.cs +++ b/zero.Core/Integrations/IntegrationService.cs @@ -6,7 +6,7 @@ namespace zero.Core.Integrations { public class IntegrationService : IntegrationsCollection, IIntegrationService { - public IntegrationService(IZeroOptions options, IZeroContext context, ILogger logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, options, logger, interceptorHandler) + public IntegrationService(IZeroOptions options, ICollectionContext context, ILogger logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, options, logger) { OnlyActive = true; } diff --git a/zero.Core/Routing/Route.cs b/zero.Core/Routing/Route.cs index 88fa7567..aae6843c 100644 --- a/zero.Core/Routing/Route.cs +++ b/zero.Core/Routing/Route.cs @@ -45,7 +45,7 @@ namespace zero.Core.Routing /// /// Contains references to the resolved collection entities /// - [Obsolete] + //[Obsolete] public List References { get; set; } = new(); /// diff --git a/zero.Core/Routing/RouteBulkRefresher.cs b/zero.Core/Routing/RouteBulkRefresher.cs index cbcc47cc..54346932 100644 --- a/zero.Core/Routing/RouteBulkRefresher.cs +++ b/zero.Core/Routing/RouteBulkRefresher.cs @@ -10,12 +10,14 @@ namespace zero.Core.Routing { public class RouteBulkRefresher { + protected IZeroDocumentSession Session { get; set; } protected IZeroStore Store { get; set; } protected IEnumerable Providers { get; set; } - public RouteBulkRefresher(IZeroStore store, IEnumerable providers) + public RouteBulkRefresher(IZeroDocumentSession session, IZeroStore store, IEnumerable providers) { + Session = session; Store = store; Providers = providers; } @@ -26,8 +28,7 @@ namespace zero.Core.Routing { int count = 0; - using IAsyncDocumentSession coreSession = Store.OpenCoreSession(); - List apps = await coreSession.Query().ToListAsync(); + List apps = await Session.Core.Query().ToListAsync(); foreach (Application app in apps) { diff --git a/zero.Core/Services/Localizer.cs b/zero.Core/Services/Localizer.cs index 7613e5f3..112a7e7e 100644 --- a/zero.Core/Services/Localizer.cs +++ b/zero.Core/Services/Localizer.cs @@ -1,5 +1,4 @@ -using Raven.Client.Documents.Session; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -11,19 +10,18 @@ using zero.Core.Renderer; namespace zero.Core.Services { - public class Localizer : ILocalizer, IDisposable + public class Localizer : ILocalizer { protected Dictionary Cache { get; private set; } = new(); protected IZeroStore Store { get; private set; } - IDocumentSession _session = null; - protected IDocumentSession Session { get { return _session ?? (_session = Store.OpenSession()); } } + protected IZeroDocumentSession Session { get; private set; } - public Localizer(IZeroStore store) + public Localizer(IZeroDocumentSession session) { - Store = store; + Session = session; } @@ -89,13 +87,6 @@ namespace zero.Core.Services } - /// - public void Dispose() - { - Session?.Dispose(); - } - - /// /// Get translation from database or any other source /// @@ -105,7 +96,7 @@ namespace zero.Core.Services } } - public interface ILocalizer : IDisposable + public interface ILocalizer { /// /// diff --git a/zero.Core/ZeroContext.cs b/zero.Core/ZeroContext.cs index e4b49ec7..3cbd46a7 100644 --- a/zero.Core/ZeroContext.cs +++ b/zero.Core/ZeroContext.cs @@ -61,8 +61,6 @@ namespace zero.Core bool _resolved = false; - ConcurrentDictionary _sessions = new(); - public ZeroContext(IZeroOptions options, IHttpContextAccessor httpContextAccessor, IApplicationResolver appResolver, ICultureResolver cultureResolver, ILogger logger, IZeroStore store, IHandlerHolder handler) { @@ -133,14 +131,6 @@ namespace zero.Core /// public void Remove() => ValueCollection.Remove(); - - - /// - public IAsyncDocumentSession GetCurrentScopeAsyncSession(string database = null) - { - database ??= Store.ResolvedDatabase; - return _sessions.GetOrAdd(database, _ => Store.OpenAsyncSession(database)); - } } @@ -197,11 +187,6 @@ namespace zero.Core /// Task Resolve(HttpContext context); - /// - /// When using one session per request, we can retrieve the current session for this request - /// - IAsyncDocumentSession GetCurrentScopeAsyncSession(string database = null); - /// /// Get a custom property from this scoped context /// diff --git a/zero.Web/Controllers/BackofficeController.cs b/zero.Web/Controllers/BackofficeController.cs index 3b9afb13..80031f35 100644 --- a/zero.Web/Controllers/BackofficeController.cs +++ b/zero.Web/Controllers/BackofficeController.cs @@ -22,12 +22,10 @@ namespace zero.Web.Controllers public abstract class BackofficeController : ControllerBase { IZeroOptions _options; - IToken _token; public bool IsCoreDatabase { get; protected set; } protected IZeroOptions Options => _options ?? (_options = HttpContext?.RequestServices?.GetService()); - protected IToken Token => _token ?? (_token = HttpContext?.RequestServices?.GetService()); /// @@ -53,7 +51,7 @@ namespace zero.Web.Controllers EditModel model = new EditModel(); model.Entity = data; - model.Meta.Token = Token.Get(data); + model.Meta.Token = null; // Token.Get(data); //model.Meta.IsAppAware = AppAwareType.IsAssignableFrom(type); // TODO appx //model.Meta.CanBeShared = canBeShared; model.Meta.CanCreate = true; @@ -79,7 +77,7 @@ namespace zero.Web.Controllers //ControllerContext.ActionDescriptor.FilterDescriptors[0]. - data.Meta.Token = Token.Get(data.Entity); + data.Meta.Token = null; // Token.Get(data.Entity); //data.Meta.IsAppAware = AppAwareType.IsAssignableFrom(type); // TODO appx //data.Meta.CanBeShared = canBeShared; data.Meta.CanCreate = true; diff --git a/zero.Web/Defaults/ZeroBackofficePlugin.cs b/zero.Web/Defaults/ZeroBackofficePlugin.cs index 8dcd4da7..462b096b 100644 --- a/zero.Web/Defaults/ZeroBackofficePlugin.cs +++ b/zero.Web/Defaults/ZeroBackofficePlugin.cs @@ -100,7 +100,6 @@ namespace zero.Web.Defaults services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -129,6 +128,8 @@ namespace zero.Web.Defaults services.AddTransient(); services.AddTransient(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); diff --git a/zero.Web/Filters/CanEditAttribute.cs b/zero.Web/Filters/CanEditAttribute.cs index 775289b0..6b5a9b94 100644 --- a/zero.Web/Filters/CanEditAttribute.cs +++ b/zero.Web/Filters/CanEditAttribute.cs @@ -13,12 +13,12 @@ namespace zero.Web.Filters private class CanEditAttributeImpl : IAsyncResultFilter { - IToken token; + //IToken token; - public CanEditAttributeImpl(IToken token) + public CanEditAttributeImpl()//IToken token) { - this.token = token; + //this.token = token; } public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) diff --git a/zero.Web/ViewHelpers/ZeroMediaHelper.cs b/zero.Web/ViewHelpers/ZeroMediaHelper.cs index a4915556..f7c7b940 100644 --- a/zero.Web/ViewHelpers/ZeroMediaHelper.cs +++ b/zero.Web/ViewHelpers/ZeroMediaHelper.cs @@ -21,13 +21,13 @@ namespace zero.Web.ViewHelpers ConcurrentDictionary Cache { get; set; } = new(); - public ZeroMediaHelper(IZeroDocumentSession session, IZeroCoreDocumentSession coreSession, bool isCore = false) + public ZeroMediaHelper(IZeroDocumentSession session, bool isCore = false) { Session = session; if (!isCore) { - Core = new ZeroMediaHelper(coreSession, coreSession, true); + Core = new ZeroMediaHelper(session.Core, true); } } diff --git a/zero.Web/ZeroBuilder.cs b/zero.Web/ZeroBuilder.cs index b6f42e38..8f707ec7 100644 --- a/zero.Web/ZeroBuilder.cs +++ b/zero.Web/ZeroBuilder.cs @@ -178,15 +178,7 @@ namespace zero.Web Services.AddScoped(services => { - var session = services.GetRequiredService()!.GetCurrentScopeAsyncSession(); - session.Advanced.WaitForIndexesAfterSaveChanges(); - return session as ZeroDocumentSession; - }); - - Services.AddScoped(services => - { - IZeroOptions options = services.GetService(); - var session = services.GetRequiredService()!.GetCurrentScopeAsyncSession(options.Raven.Database); + var session = services.GetRequiredService().OpenAsyncSession(); session.Advanced.WaitForIndexesAfterSaveChanges(); return session as ZeroDocumentSession; });