This commit is contained in:
2026-11-15 17:52:54 +03:30
parent 24363e89ae
commit 3a556a329a
8 changed files with 2727 additions and 8 deletions
+19
View File
@@ -19,6 +19,7 @@ using xCommons.Authorization;
using System.Collections.Generic;
using xMessageService.Interfaces;
using xStorageService.Interfaces;
using xIdentityModels.Interfaces;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
@@ -81,6 +82,20 @@ namespace xIds.DI
return config.GetConnectionString(connectionName);
}
/// <summary>
/// Register Scope/Role/Policy Providers ...
/// </summary>
/// <param name="source"></param>
public static void AddXAuthorizationProviders(
this IServiceCollection source
)
{
//
source.AddScoped<IXRoleProvider, XRoleProvider>();
source.AddScoped<IXScopeProvider, XScopeProvider>();
source.AddScoped<IXPolicyProvider, XPolicyProvider>();
}
/// <summary>
/// Retrive XDataService Configurations ...
/// </summary>
@@ -531,6 +546,10 @@ namespace xIds.DI
//
services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>();
//
// Register Providers ...
services.AddXAuthorizationProviders();
}
/// <summary>
+3
View File
@@ -20,6 +20,9 @@ namespace xIds.DbContext
public DbSet<XBannedDevice> BannedDevices { get; set; }
public DbSet<XFriendshipFollower> Followers { get; set; }
public DbSet<XFriendshipFollowing> Followings { get; set; }
public DbSet<XRoleDefinition> RoleDefinitions { get; set; }
public DbSet<XScopeDefinition> ScopeDefinitions { get; set; }
public DbSet<XPolicyDefinition> PolicyDefinitions { get; set; }
public DbSet<XVerificationRequest> VerificationRequests { get; set; }
#endregion
+315
View File
@@ -1,8 +1,13 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Reflection;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xDataService.Constants;
using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic;
using xDataService.Configuration;
using Microsoft.EntityFrameworkCore;
@@ -32,6 +37,146 @@ namespace xIds.Extensions
return result;
}
// /// <summary>
// /// Apply Search Filter on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="filter"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplyFilter<T>(
// this IEnumerable<T> source,
// string filter
// )
// where T : class
// {
// //
// // Apply Filter ...
// return source.Where(r => r.PropValuesContains(filter));
// }
// /// <summary>
// /// Count Query Pages based on Specified Total Number ...
// /// </summary>
// /// <param name="source"></param>
// /// <param name="totalItems"></param>
// /// <returns></returns>
// public static int CountPages(
// this XQuery source,
// int totalItems
// )
// {
// //
// int result = 0;
// //
// // Validate and Calculate ...
// if (!source.IsNull() && source.PageSize > 0 && totalItems > 0)
// {
// //
// result = totalItems / source.PageSize;
// if (totalItems % source.PageSize > 0)
// {
// result++;
// }
// }
// //
// return result;
// }
// /// <summary>
// /// Apply Sorting on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="sortBy"></param>
// /// <param name="isAscending"></param>
// /// <param name="columnsMap"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplySorting<T>(
// this IEnumerable<T> source,
// string sortBy,
// bool isAscending,
// IDictionary<string, Expression<Func<T, object>>> columnsMap = null
// )
// where T : class
// {
// //
// if (columnsMap == null)
// {
// //
// columnsMap = source.FirstOrDefault()
// .GetDefaultColumnsMap();
// //
// if (columnsMap == null)
// {
// return source;
// }
// }
// //
// // Validate SortBy ...
// var sortByItem = columnsMap.Keys
// .FirstOrDefault(p =>
// p.ToNormalString() == sortBy.ToNormalString());
// if (sortByItem.IsNullOrEmpty())
// {
// return source;
// }
// //
// // Apply Sorting ...
// if (isAscending)
// {
// return source.OrderBy(sortByItem);
// }
// else
// {
// return source.OrderByDescending(sortByItem);
// }
// }
// /// <summary>
// /// Apply Paging on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="page"></param>
// /// <param name="pageSize"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplyPaging<T>(
// this IEnumerable<T> source,
// int? page,
// int? pageSize
// )
// {
// //
// if (!page.HasValue ||
// page <= 0)
// {
// page = 1;
// }
// //
// if (!pageSize.HasValue ||
// pageSize <= 0 ||
// pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE)
// {
// pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE;
// }
// //
// var pageVal = page.GetValueOrDefault();
// var pageSizeVal = pageSize.GetValueOrDefault();
// //
// return source
// .Skip((pageVal - 1) * pageSizeVal)
// .Take(pageSizeVal);
// }
/// <summary>
/// Applying Filter to IQueryable
/// /// </summary>
@@ -87,5 +232,175 @@ namespace xIds.Extensions
//
return result;
}
// /// <summary>
// /// provide a way to Order an IQueryable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedQueryable<TSource> OrderBy<TSource>(
// this IQueryable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// //
// // Create x => x.PropName
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// ParameterExpression arg = Expression.Parameter(entityType, "x");
// MemberExpression property = Expression.Property(arg, propertyName);
// var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
// //
// // Get System.Linq.Queryable.OrderBy() method.
// var enumarableType = typeof(System.Linq.Queryable);
// var method = enumarableType.GetMethods()
// .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition)
// .Where(m =>
// {
// //
// var parameters = m.GetParameters().ToList();
// //
// // Put more restriction here to ensure selecting the right overload
// return parameters.Count == 2; // overload that has 2 parameters
// }).Single();
// //
// // The linq's OrderBy<TSource, TKey> has two generic types, which provided here ...
// MethodInfo genericMethod = method
// .MakeGenericMethod(entityType, propertyInfo.PropertyType);
// /*
// Call query.OrderBy(selector), with query and selector: x=> x.PropName
// Note that we pass the selector as Expression to the method and we don't compile it.
// By doing so EF can extract "order by" columns and generate SQL for it.
// */
// var newQuery = (IOrderedQueryable<TSource>)genericMethod
// .Invoke(genericMethod, new object[] { query, selector });
// //
// return newQuery;
// }
// /// <summary>
// /// provide a way to Order an IEnumerable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedEnumerable<TSource> OrderBy<TSource>(
// this IEnumerable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// return query.OrderBy(x => propertyInfo.GetValue(x, null));
// }
// /// <summary>
// /// provide a way to Order an IQueryable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedQueryable<TSource> OrderByDescending<TSource>(
// this IQueryable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// //
// // Create x => x.PropName
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// ParameterExpression arg = Expression.Parameter(entityType, "x");
// MemberExpression property = Expression.Property(arg, propertyName);
// var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
// //
// // Get System.Linq.Queryable.OrderBy() method.
// var enumarableType = typeof(System.Linq.Queryable);
// var method = enumarableType.GetMethods()
// .Where(m => m.Name == "OrderByDescending" && m.IsGenericMethodDefinition)
// .Where(m =>
// {
// //
// var parameters = m.GetParameters().ToList();
// //
// // Put more restriction here to ensure selecting the right overload
// return parameters.Count == 2; // overload that has 2 parameters
// }).Single();
// //
// // The linq's OrderBy<TSource, TKey> has two generic types, which provided here ...
// MethodInfo genericMethod = method
// .MakeGenericMethod(entityType, propertyInfo.PropertyType);
// /*
// Call query.OrderBy(selector), with query and selector: x=> x.PropName
// Note that we pass the selector as Expression to the method and we don't compile it.
// By doing so EF can extract "order by" columns and generate SQL for it.
// */
// var newQuery = (IOrderedQueryable<TSource>)genericMethod
// .Invoke(genericMethod, new object[] { query, selector });
// //
// return newQuery;
// }
// /// <summary>
// /// provide a way to Order an IEnumerable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(
// this IEnumerable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// return query.OrderByDescending(x => propertyInfo.GetValue(x, null));
// }
}
}
+1 -1
View File
@@ -1,4 +1,5 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
@@ -14,7 +15,6 @@ using IdentityServer4.Extensions;
using xIdentityModels.Extensions;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.Caching.Memory;
using AutoMapper;
namespace xIds.Providers
{
@@ -1,11 +1,11 @@
using System.Threading.Tasks;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityModels.Dtos;
using xModels.Dtos;
using xDataService.Extensions;
using xIds.Extensions;
using System.Linq;
using xModels.Dtos;
using xIds.Extensions;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xDataService.Extensions;
using xIdentityModels.Extensions;
namespace xIds.Providers
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xCommons.Extensions;
using xIds.Configurations;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Linq.Expressions;
using xDataService.Extensions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityModels.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XPolicyProvider : IXPolicyProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XPolicyProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XPolicyDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null
)
{
//
var result = dbContext.PolicyDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> FindOneAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> FindManyAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XPolicyDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XPolicyDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> AddAsync(
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XPolicyDefinition, XPolicyDefinitionDto>();
var entry = await dbContext.PolicyDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> UpdateAsync(
int id,
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.PolicyDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.PolicyDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.PolicyDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XPolicyDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.PolicyDefinitions.Update(exists);
}
else
{
entry = dbContext.PolicyDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XPolicyDefinitionDto, XPolicyDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xIds.Configurations;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using xIdentityModels.Models;
using System.Threading.Tasks;
using xDataService.Extensions;
using System.Linq.Expressions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityModels.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XRoleProvider : IXRoleProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XRoleProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XRoleDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null
)
{
//
var result = dbContext.RoleDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> FindOneAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> FindManyAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XRoleDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XRoleDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> AddAsync(
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XRoleDefinition, XRoleDefinitionDto>();
var entry = await dbContext.RoleDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> UpdateAsync(
int id,
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.RoleDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.RoleDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.RoleDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XRoleDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.RoleDefinitions.Update(exists);
}
else
{
entry = dbContext.RoleDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XRoleDefinitionDto, XRoleDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xCommons.Extensions;
using xIds.Configurations;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xDataService.Extensions;
using System.Linq.Expressions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityModels.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XScopeProvider : IXScopeProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XScopeProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XScopeDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null
)
{
//
var result = dbContext.ScopeDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> FindOneAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> FindManyAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XScopeDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XScopeDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> AddAsync(
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XScopeDefinition, XScopeDefinitionDto>();
var entry = await dbContext.ScopeDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> UpdateAsync(
int id,
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.ScopeDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.ScopeDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.ScopeDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XScopeDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.ScopeDefinitions.Update(exists);
}
else
{
entry = dbContext.ScopeDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XScopeDefinitionDto, XScopeDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}