Unify raven session

This commit is contained in:
2021-10-13 12:47:18 +02:00
parent b48e679a0c
commit d2032370ea
36 changed files with 387 additions and 458 deletions
+4 -5
View File
@@ -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<Application> Validator;
public ApplicationsApi(IBackofficeStore store, IValidator<Application> validator) : base(store, isCoreDatabase: true)
public ApplicationsApi(ICollectionContext store, IValidator<Application> validator) : base(store, isCoreDatabase: true)
{
Validator = validator;
}
@@ -29,8 +30,7 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<IList<Application>> GetAll()
{
using IAsyncDocumentSession session = Session();
return await session
return await Session
.Query<Application>()
.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<Application>().ToQueriedListAsync(query);
return await Session.Query<Application>().ToQueriedListAsync(query);
}
+5 -6
View File
@@ -19,14 +19,14 @@ namespace zero.Core.Api
protected SignInManager<BackofficeUser> SignInManager { get; private set; }
protected IZeroStore Store { get; set; }
protected IZeroDocumentSession Session { get; set; }
public AuthenticationApi(IZeroContext context, SignInManager<BackofficeUser> signInManager, IZeroStore store)
public AuthenticationApi(IZeroContext context, SignInManager<BackofficeUser> 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;
}
+24 -35
View File
@@ -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<T>(id);
return await Session.LoadAsync<T>(id);
}
/// <inheritdoc />
public async Task<Dictionary<string, T>> GetByIds<T>(params string[] ids) where T : ZeroIdEntity
{
using IAsyncDocumentSession session = Session();
Dictionary<string, T> models = await session.LoadAsync<T>(ids);
Dictionary<string, T> models = await Session.LoadAsync<T>(ids);
Dictionary<string, T> result = new Dictionary<string, T>();
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<T>.Success(model);
}
@@ -177,19 +168,18 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<EntityResult<T>> DeleteById<T>(string id) where T : ZeroIdEntity
{
using IAsyncDocumentSession session = Session();
session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false);
Session.Advanced.WaitForIndexesAfterSaveChanges(throwOnTimeout: false);
T entity = await session.LoadAsync<T>(id);
T entity = await Session.LoadAsync<T>(id);
if (entity == null)
{
return EntityResult<T>.Fail("@errors.ondelete.idnotfound");
}
session.Delete(entity);
Session.Delete(entity);
await session.SaveChangesAsync();
await Session.SaveChangesAsync();
return EntityResult<T>.Success();
}
@@ -213,8 +203,7 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<EntityResult<T>> Purge<T>(string querySuffix = null, Parameters parameters = null)
{
string database = IsCoreDatabase ? Backoffice.Options.Raven.Database : null;
await Store.PurgeAsync<T>(database, querySuffix, parameters);
await Store.PurgeAsync<T>(Session.Advanced.DocumentStore.Database, querySuffix, parameters);
return EntityResult<T>.Success();
}
}
+9 -17
View File
@@ -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
/// <inheritdoc />
public async Task<string> 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<Media>(id);
@@ -69,10 +70,7 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<Dictionary<string, Media>> GetById(IEnumerable<string> ids)
{
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.LoadAsync<Media>(ids);
}
return await Session.LoadAsync<Media>(ids);
}
@@ -81,12 +79,9 @@ namespace zero.Core.Api
{
query.SearchFor(entity => entity.Name);
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<Media>()
.WhereIf(x => x.FolderId == query.FolderId, !query.FolderId.IsNullOrEmpty(), x => x.FolderId == null)
.ToQueriedListAsync(query);
}
return await Session.Query<Media>()
.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<MediaListItem> dbQuery = session.Query<MediaListItem, Media_ByParent>().ProjectInto<MediaListItem>();
IRavenQueryable<MediaListItem> dbQuery = Session.Query<MediaListItem, Media_ByParent>().ProjectInto<MediaListItem>();
if (!hasSearch || !query.SearchIsGlobal)
{
@@ -118,7 +110,7 @@ namespace zero.Core.Api
{
if (item.IsFolder)
{
item.Children = await session.Query<MediaListItem, Media_ByParent>().CountAsync(x => x.ParentId == item.Id);
item.Children = await Session.Query<MediaListItem, Media_ByParent>().CountAsync(x => x.ParentId == item.Id);
}
}
+66 -74
View File
@@ -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<MediaFolder> Validator;
public MediaFolderApi(IBackofficeStore store, IValidator<MediaFolder> validator) : base(store)
public MediaFolderApi(ICollectionContext store, IValidator<MediaFolder> validator) : base(store)
{
Validator = validator;
}
@@ -33,13 +34,10 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<IList<MediaFolder>> GetAll(string parentId = null)
{
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<MediaFolder>()
.WhereIf(x => x.ParentId == parentId, !parentId.IsNullOrEmpty(), x => x.ParentId == null)
.OrderByDescending(x => x.Name)
.ToListAsync();
}
return await Session.Query<MediaFolder>()
.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<TreeItem> items = new List<TreeItem>();
string[] openIds = new string[0] { };
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
IList<MediaFolder> folders = await Session.Query<MediaFolder>()
.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<MediaFolder> folders = await session.Query<MediaFolder>()
.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<MediaFolder_ByHierarchy.Result, MediaFolder_ByHierarchy>()
.ProjectInto<MediaFolder_ByHierarchy.Result>()
.Include<MediaFolder_ByHierarchy.Result, MediaFolder>(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<MediaFolder_ByHierarchy.Result, MediaFolder_ByHierarchy>()
.ProjectInto<MediaFolder_ByHierarchy.Result>()
.Include<MediaFolder_ByHierarchy.Result, MediaFolder>(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<MediaFolders_WithChildren.Result> children = await session.Query<MediaFolders_WithChildren.Result, MediaFolders_WithChildren>()
.ProjectInto<MediaFolders_WithChildren.Result>()
.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<MediaFolders_WithChildren.Result> children = await Session.Query<MediaFolders_WithChildren.Result, MediaFolders_WithChildren>()
.ProjectInto<MediaFolders_WithChildren.Result>()
.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
/// <inheritdoc />
public async Task<IList<MediaFolder>> GetHierarchy(string id)
{
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
MediaFolder_ByHierarchy.Result result = await Session.Query<MediaFolder_ByHierarchy.Result, MediaFolder_ByHierarchy>()
.ProjectInto<MediaFolder_ByHierarchy.Result>()
.Include<MediaFolder_ByHierarchy.Result, MediaFolder>(x => x.Path.Select(p => p.Id))
.FirstOrDefaultAsync(x => x.Id == id);
if (result == null)
{
MediaFolder_ByHierarchy.Result result = await session.Query<MediaFolder_ByHierarchy.Result, MediaFolder_ByHierarchy>()
.ProjectInto<MediaFolder_ByHierarchy.Result>()
.Include<MediaFolder_ByHierarchy.Result, MediaFolder>(x => x.Path.Select(p => p.Id))
.FirstOrDefaultAsync(x => x.Id == id);
if (result == null)
{
return new List<MediaFolder>();
}
List<string> ids = result.Path.Select(x => x.Id).ToList();
ids.Add(id);
return (await session.LoadAsync<MediaFolder>(ids)).Select(x => x.Value).ToList();
return new List<MediaFolder>();
}
List<string> ids = result.Path.Select(x => x.Id).ToList();
ids.Add(id);
return (await Session.LoadAsync<MediaFolder>(ids)).Select(x => x.Value).ToList();
}
+3 -2
View File
@@ -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();
}
+7 -9
View File
@@ -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<IList<TreeItem>> GetChildren(string parentId = null, string activeId = null, string search = null)
{
IList<TreeItem> items = new List<TreeItem>();
IReadOnlyCollection<PageType> pageTypes = Backoffice.Options.Pages.GetAllItems();
IReadOnlyCollection<PageType> pageTypes = Context.Options.Pages.GetAllItems();
string[] openIds = new string[0] { };
IList<Page> pages = null;
IList<Pages_WithChildren.Result> children = null;
bool isSearch = !search.IsNullOrWhiteSpace();
using IAsyncDocumentSession session = Store.OpenAsyncSession();
if (isSearch)
{
pages = await session
pages = await Session
.Query<Page>()
.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<Page>()
.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, Pages_ByHierarchy>()
Pages_ByHierarchy.Result result = await Session.Query<Pages_ByHierarchy.Result, Pages_ByHierarchy>()
.ProjectInto<Pages_ByHierarchy.Result>()
.Include<Pages_ByHierarchy.Result, Page>(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<Pages_WithChildren.Result, Pages_WithChildren>()
children = await Session.Query<Pages_WithChildren.Result, Pages_WithChildren>()
.ProjectInto<Pages_WithChildren.Result>()
.Where(x => x.Id.In(pageIds))
.ToListAsync();
+2 -1
View File
@@ -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;
}
+12 -20
View File
@@ -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<RecycledEntity>()
.WhereIf(x => x.Group == query.Group, !query.Group.IsNullOrWhiteSpace())
.WhereIf(x => x.OperationId == query.OperationId, !query.OperationId.IsNullOrWhiteSpace())
.ToQueriedListAsync(query);
}
return await Session.Query<RecycledEntity>()
.WhereIf(x => x.Group == query.Group, !query.Group.IsNullOrWhiteSpace())
.WhereIf(x => x.OperationId == query.OperationId, !query.OperationId.IsNullOrWhiteSpace())
.ToQueriedListAsync(query);
}
/// <inheritdoc />
public async Task<IList<RecycledEntity>> GetByOperation(string operationId)
{
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<RecycledEntity>()
.Where(x => x.OperationId == operationId)
.ToListAsync();
}
return await Session.Query<RecycledEntity>()
.Where(x => x.OperationId == operationId)
.ToListAsync();
}
@@ -94,12 +89,9 @@ namespace zero.Core.Api
/// </summary>
public async Task<int> GetCountByOperation(string operationId)
{
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<RecycledEntity>()
.Where(x => x.OperationId == operationId)
.CountAsync();
}
return await Session.Query<RecycledEntity>()
.Where(x => x.OperationId == operationId)
.CountAsync();
}
+30 -48
View File
@@ -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
/// <inheritdoc />
public IReadOnlyCollection<Space> GetAll()
{
return Backoffice.Options.Spaces.GetAllItems();
return Context.Options.Spaces.GetAllItems();
}
@@ -47,14 +48,10 @@ namespace zero.Core.Api
public async Task<SpaceContent> GetItem(string alias, string id = null)
{
Space space = GetByAlias(alias);
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<SpaceContent>()
.Where(x => x.SpaceAlias == space.Alias)
.WhereIf(x => x.Id == id, !id.IsNullOrEmpty())
.FirstOrDefaultAsync();
}
return await Session.Query<SpaceContent>()
.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<T>();
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<T>()
.Where(x => x.SpaceAlias == space.Alias)
.WhereIf(x => x.Id == id, !id.IsNullOrEmpty())
.FirstOrDefaultAsync();
}
return await Session.Query<T>()
.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<T>();
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
ids = ids.Distinct().ToArray();
Dictionary<string, T> models = await Session.LoadAsync<T>(ids);
Dictionary<string, T> result = new Dictionary<string, T>();
foreach (string id in ids)
{
ids = ids.Distinct().ToArray();
Dictionary<string, T> models = await session.LoadAsync<T>(ids);
Dictionary<string, T> result = new Dictionary<string, T>();
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<SpaceContent>()
.Where(x => x.SpaceAlias == alias)
.ToQueriedListAsync(query);
}
return await Session.Query<SpaceContent>()
.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<T>()
.Where(x => x.SpaceAlias == alias)
.ToQueriedListAsync(query);
}
return await Session.Query<T>()
.Where(x => x.SpaceAlias == alias)
.ToQueriedListAsync(query);
}
@@ -130,12 +115,9 @@ namespace zero.Core.Api
Space space = GetBy<T>();
query.SearchSelector = item => item.Name;
using (IAsyncDocumentSession session = Store.OpenAsyncSession())
{
return await session.Query<T>()
.Where(x => x.SpaceAlias == space.Alias)
.ToQueriedListAsync(query);
}
return await Session.Query<T>()
.Where(x => x.SpaceAlias == space.Alias)
.ToQueriedListAsync(query);
}
+88 -88
View File
@@ -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;
// }
/// <inheritdoc />
public bool Verify(ZeroIdEntity entity, string token)
{
return Verify(entity?.Id, token);
}
// /// <inheritdoc />
// public bool Verify(ZeroIdEntity entity, string token)
// {
// return Verify(entity?.Id, token);
// }
/// <inheritdoc />
public bool Verify(string entityId, string token)
{
if (token.IsNullOrWhiteSpace() && entityId.IsNullOrEmpty())
{
return true;
}
// /// <inheritdoc />
// 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<ChangeToken>().Any(x => x.Id == token && x.ReferenceId == entityId);
}
}
// using (IDocumentSession session = Store.OpenSession())
// {
// return session.Query<ChangeToken>().Any(x => x.Id == token && x.ReferenceId == entityId);
// }
// }
/// <inheritdoc />
public string Get(ZeroIdEntity entity)
{
return Get(entity?.Id);
}
// /// <inheritdoc />
// public string Get(ZeroIdEntity entity)
// {
// return Get(entity?.Id);
// }
/// <inheritdoc />
public string Get(string entityId)
{
if (entityId.IsNullOrEmpty())
{
return null;
}
// /// <inheritdoc />
// 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
{
/// <summary>
/// Verifies if the change token is valid for the entity
/// </summary>
bool Verify(ZeroIdEntity entity, string token);
// public interface IToken
// {
// /// <summary>
// /// Verifies if the change token is valid for the entity
// /// </summary>
// bool Verify(ZeroIdEntity entity, string token);
/// <summary>
/// Verifies if the change token is valid for the entity
/// </summary>
bool Verify(string entityId, string token);
// /// <summary>
// /// Verifies if the change token is valid for the entity
// /// </summary>
// bool Verify(string entityId, string token);
/// <summary>
/// Get a new change token for the entity
/// </summary>
string Get(ZeroIdEntity entity);
// /// <summary>
// /// Get a new change token for the entity
// /// </summary>
// string Get(ZeroIdEntity entity);
/// <summary>
/// Get a new change token for the entity
/// </summary>
string Get(string entityId);
}
}
// /// <summary>
// /// Get a new change token for the entity
// /// </summary>
// string Get(string entityId);
// }
//}
+5 -9
View File
@@ -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<BackofficeUser> UserManager { get; private set; }
protected IZeroContext Context { get; set; }
public UserApi(IBackofficeStore store, UserManager<BackofficeUser> userManager, IZeroContext context) : base(store, isCoreDatabase: true)
public UserApi(ICollectionContext store, UserManager<BackofficeUser> userManager) : base(store, isCoreDatabase: true)
{
UserManager = userManager;
Context = context;
}
@@ -49,8 +47,7 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<IList<BackofficeUser>> GetAll()
{
using IAsyncDocumentSession session = Session();
return await session.Query<BackofficeUser>()
return await Session.Query<BackofficeUser>()
.OrderByDescending(x => x.CreatedDate)
.ToListAsync();
}
@@ -59,12 +56,11 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<ListResult<BackofficeUser>> GetByQuery(ListQuery<BackofficeUser> 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<BackofficeUser>()
return await Session.Query<BackofficeUser>()
.ToQueriedListAsync(query);
}
+19 -25
View File
@@ -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<BackofficeUser> userManager, RoleManager<BackofficeUserRole> roleManager, IBackofficeStore store) : base(store, isCoreDatabase: true)
public UserRolesApi(IHttpContextAccessor httpContextAccessor, UserManager<BackofficeUser> userManager, RoleManager<BackofficeUserRole> roleManager, ICollectionContext store) : base(store, isCoreDatabase: true)
{
HttpContextAccessor = httpContextAccessor;
UserManager = userManager;
@@ -37,8 +38,7 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<IList<BackofficeUserRole>> GetAll()
{
using IAsyncDocumentSession session = Session();
return await session.Query<BackofficeUserRole>().OrderBy(x => x.Sort).ThenBy(x => x.Name).ToListAsync();
return await Session.Query<BackofficeUserRole>().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<BackofficeUserRole>.Success(model);
@@ -87,20 +84,17 @@ namespace zero.Core.Api
/// <inheritdoc />
public async Task<EntityResult<BackofficeUserRole>> Delete(string id)
{
using (IAsyncDocumentSession session = Session())
BackofficeUserRole country = await Session.LoadAsync<BackofficeUserRole>(id);
if (country == null)
{
BackofficeUserRole country = await session.LoadAsync<BackofficeUserRole>(id);
if (country == null)
{
return EntityResult<BackofficeUserRole>.Fail("@errors.ondelete.idnotfound");
}
session.Delete(country);
await session.SaveChangesAsync();
return EntityResult<BackofficeUserRole>.Fail("@errors.ondelete.idnotfound");
}
Session.Delete(country);
await Session.SaveChangesAsync();
return EntityResult<BackofficeUserRole>.Success();
}
}
+9 -21
View File
@@ -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<T> : ICollectionBase<T>, 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<T> PreSave { get; set; }
protected bool OnlyActive { get; set; } = false; // TODO do we really need this?
public CollectionBase(IZeroContext context, ICollectionInterceptorHandler interceptorHandler = null, IValidator<T> validator = null)
public CollectionBase(ICollectionContext collectionContext, IValidator<T> 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
/// <summary>
/// Create an an async document session
/// </summary>
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;
/// <inheritdoc />
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
/// <summary>
/// Create an async document session
/// </summary>
IAsyncDocumentSession Session { get; }
IZeroDocumentSession Session { get; }
/// <summary>
/// Applies the scope to the service instance
@@ -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; }
}
}
@@ -9,7 +9,7 @@ namespace zero.Core.Collections
{
public class CountriesCollection : CollectionBase<Country>, ICountriesCollection
{
public CountriesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator<Country> validator) : base(context, interceptor, validator) { }
public CountriesCollection(ICollectionContext context, IValidator<Country> validator) : base(context, validator) { }
/// <inheritdoc />
@@ -22,7 +22,7 @@ namespace zero.Core.Collections
protected ILogger<IntegrationsCollection> Logger { get; private set; }
public IntegrationsCollection(IZeroContext context, IZeroOptions options, ILogger<IntegrationsCollection> logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, interceptorHandler)
public IntegrationsCollection(ICollectionContext context, IZeroOptions options, ILogger<IntegrationsCollection> logger) : base(context)
{
Options = options;
RegisteredTypes = Options.Integrations.GetAllItems();
@@ -12,7 +12,7 @@ namespace zero.Core.Collections
{
public class LanguagesCollection : CollectionBase<Language>, ILanguagesCollection
{
public LanguagesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator<Language> validator) : base(context, interceptor, validator) { }
public LanguagesCollection(ICollectionContext context, IValidator<Language> validator) : base(context, validator) { }
/// <inheritdoc />
@@ -7,7 +7,7 @@ namespace zero.Core.Collections
{
public class MailTemplatesCollection : CollectionBase<MailTemplate>, IMailTemplatesCollection
{
public MailTemplatesCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator<MailTemplate> validator) : base(context, interceptor, validator) { }
public MailTemplatesCollection(ICollectionContext context, IValidator<MailTemplate> validator) : base(context, validator) { }
/// <inheritdoc />
+2 -23
View File
@@ -21,34 +21,13 @@ namespace zero.Core.Collections
{
public class MediaCollection : CollectionBase<Media>, IMediaCollection
{
private IAsyncDocumentSession _coreSession;
public MediaCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator<Media> validator, IPaths paths) : base(context, interceptor, validator)
public MediaCollection(ICollectionContext context, IValidator<Media> validator, IPaths paths) : base(context, validator)
{
PreSave = model => model.IsActive = true;
Paths = paths;
}
/// <summary>
/// Create an an async document session
/// </summary>
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<Media>(coreIds);
models = await Session.Core.LoadAsync<Media>(coreIds);
foreach (string id in coreIds)
{
models.TryGetValue(id, out Media model);
@@ -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<IPagesCollection> logger, IValidator<Page> validator = null) : base(context, interceptor, validator)
public PagesCollection(ICollectionContext context, IRecycleBinApi recycleBinApi, IHandlerHolder handler,
ILogger<IPagesCollection> logger, IValidator<Page> validator = null) : base(context, validator)
{
RecycleBinApi = recycleBinApi;
Handler = handler;
@@ -9,7 +9,7 @@ namespace zero.Core.Collections
{
public class TranslationsCollection : CollectionBase<Translation>, ITranslationsCollection
{
public TranslationsCollection(IZeroContext context, ICollectionInterceptorHandler interceptor, IValidator<Translation> validator) : base(context, interceptor, validator) { }
public TranslationsCollection(ICollectionContext context, IValidator<Translation> validator) : base(context, validator) { }
/// <inheritdoc />
+4 -1
View File
@@ -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<Language>().FirstOrDefaultAsync();
using IAsyncDocumentSession session = context.Store.OpenAsyncSession();
Language language = await session.Query<Language>().FirstOrDefaultAsync();
if (language == null)
{
+22 -9
View File
@@ -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; }
}
}
+1 -1
View File
@@ -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);
+3 -3
View File
@@ -8,7 +8,7 @@ namespace zero.Core.Identity
public class RavenCoreRoleStore<TRole> : RavenRoleStore<TRole>
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<TUser> : RavenUserStore<TUser>
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) { }
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ namespace zero.Core.Integrations
{
public class IntegrationService : IntegrationsCollection, IIntegrationService
{
public IntegrationService(IZeroOptions options, IZeroContext context, ILogger<IntegrationsCollection> logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, options, logger, interceptorHandler)
public IntegrationService(IZeroOptions options, ICollectionContext context, ILogger<IntegrationsCollection> logger, ICollectionInterceptorHandler interceptorHandler = null) : base(context, options, logger)
{
OnlyActive = true;
}
+1 -1
View File
@@ -45,7 +45,7 @@ namespace zero.Core.Routing
/// <summary>
/// Contains references to the resolved collection entities
/// </summary>
[Obsolete]
//[Obsolete]
public List<RouteReference> References { get; set; } = new();
/// <summary>
+4 -3
View File
@@ -10,12 +10,14 @@ namespace zero.Core.Routing
{
public class RouteBulkRefresher
{
protected IZeroDocumentSession Session { get; set; }
protected IZeroStore Store { get; set; }
protected IEnumerable<IRouteProvider> Providers { get; set; }
public RouteBulkRefresher(IZeroStore store, IEnumerable<IRouteProvider> providers)
public RouteBulkRefresher(IZeroDocumentSession session, IZeroStore store, IEnumerable<IRouteProvider> providers)
{
Session = session;
Store = store;
Providers = providers;
}
@@ -26,8 +28,7 @@ namespace zero.Core.Routing
{
int count = 0;
using IAsyncDocumentSession coreSession = Store.OpenCoreSession();
List<Application> apps = await coreSession.Query<Application>().ToListAsync();
List<Application> apps = await Session.Core.Query<Application>().ToListAsync();
foreach (Application app in apps)
{
+6 -15
View File
@@ -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<string, string> 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
}
/// <inheritdoc />
public void Dispose()
{
Session?.Dispose();
}
/// <summary>
/// Get translation from database or any other source
/// </summary>
@@ -105,7 +96,7 @@ namespace zero.Core.Services
}
}
public interface ILocalizer : IDisposable
public interface ILocalizer
{
/// <summary>
///
-15
View File
@@ -61,8 +61,6 @@ namespace zero.Core
bool _resolved = false;
ConcurrentDictionary<string, IAsyncDocumentSession> _sessions = new();
public ZeroContext(IZeroOptions options, IHttpContextAccessor httpContextAccessor, IApplicationResolver appResolver, ICultureResolver cultureResolver, ILogger<ZeroContext> logger, IZeroStore store, IHandlerHolder handler)
{
@@ -133,14 +131,6 @@ namespace zero.Core
/// <inheritdoc />
public void Remove<T>() => ValueCollection.Remove<T>();
/// <inheritdoc />
public IAsyncDocumentSession GetCurrentScopeAsyncSession(string database = null)
{
database ??= Store.ResolvedDatabase;
return _sessions.GetOrAdd(database, _ => Store.OpenAsyncSession(database));
}
}
@@ -197,11 +187,6 @@ namespace zero.Core
/// </summary>
Task Resolve(HttpContext context);
/// <summary>
/// When using one session per request, we can retrieve the current session for this request
/// </summary>
IAsyncDocumentSession GetCurrentScopeAsyncSession(string database = null);
/// <summary>
/// Get a custom property from this scoped context
/// </summary>
+2 -4
View File
@@ -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<IZeroOptions>());
protected IToken Token => _token ?? (_token = HttpContext?.RequestServices?.GetService<IToken>());
/// <summary>
@@ -53,7 +51,7 @@ namespace zero.Web.Controllers
EditModel<T> model = new EditModel<T>();
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;
+2 -1
View File
@@ -100,7 +100,6 @@ namespace zero.Web.Defaults
services.AddTransient<ISettingsApi, SettingsApi>();
services.AddTransient<IAuthenticationApi, AuthenticationApi>();
services.AddTransient<IUserRolesApi, UserRolesApi>();
services.AddTransient<IToken, Token>();
services.AddTransient<ISpacesApi, SpacesApi>();
services.AddTransient<IPermissionsApi, PermissionsApi>();
services.AddTransient<IMediaApi, MediaApi>();
@@ -129,6 +128,8 @@ namespace zero.Web.Defaults
services.AddTransient<IIntegrationService, IntegrationService>();
services.AddTransient<IIntegrationsCollection, IntegrationsCollection>();
services.AddScoped<ICollectionContext, CollectionContext>();
services.AddScoped<ILocalizer, Localizer>();
services.AddScoped<IZeroTokenProvider, ZeroTokenProvider>();
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -21,13 +21,13 @@ namespace zero.Web.ViewHelpers
ConcurrentDictionary<string, Media> 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);
}
}
+1 -9
View File
@@ -178,15 +178,7 @@ namespace zero.Web
Services.AddScoped<IZeroDocumentSession>(services =>
{
var session = services.GetRequiredService<IZeroContext>()!.GetCurrentScopeAsyncSession();
session.Advanced.WaitForIndexesAfterSaveChanges();
return session as ZeroDocumentSession;
});
Services.AddScoped<IZeroCoreDocumentSession>(services =>
{
IZeroOptions options = services.GetService<IZeroOptions>();
var session = services.GetRequiredService<IZeroContext>()!.GetCurrentScopeAsyncSession(options.Raven.Database);
var session = services.GetRequiredService<IZeroStore>().OpenAsyncSession();
session.Advanced.WaitForIndexesAfterSaveChanges();
return session as ZeroDocumentSession;
});