public bool TryAddDbExecutor(IDbExecutor dbExecutor) { CheckValue.NotNull(dbExecutor, nameof(dbExecutor)); //added executor.Guarantee that it will eventually be released AddedExecutors.AddIfNotContains(dbExecutor); if (!EnsureToOpenTransaction()) { return(true); } if (dbExecutor.HasTransaction) { return(true); } bool result = false; var transactionObj = OpenTransactionAndGiveExecutor(_transactions, dbExecutor); if (transactionObj != null) { //reused or new? if (!CreatedTransactions.Any(s => s.ID == transactionObj.ID)) { CreatedTransactions.Add(transactionObj); } result = true; } return(result); }
/// <summary> /// <inheritdoc/> /// </summary> public virtual object WrapFailedResult(object originalData, Exception exception, DataWrapperContext wrapperContext) { var httpContext = wrapperContext.HttpContext; var options = wrapperContext.WrapperOptions; CheckValue.NotNull(httpContext, nameof(HttpContext)); CheckValue.NotNull(options, nameof(DataWrapperOptions)); if (exception is ISoftlyMiCakeException) { //Given Ok Code for this exception. httpContext.Response.StatusCode = StatusCodes.Status200OK; //Given this exception to context. wrapperContext.SoftlyException = exception as SoftlyMiCakeException; return(WrapSuccesfullysResult(originalData ?? exception.Message, wrapperContext, true)); } var micakeException = exception as MiCakeException; ApiError result = new ApiError(exception.Message, originalData, micakeException?.Code, options.IsDebug ? exception.StackTrace : null); return(result); }
public MiCakeHandlerDescriptor(IMiCakeHandler handler, bool isFromFactory = false) { CheckValue.NotNull(handler, nameof(handler)); Handler = handler; IsFromFactory = IsFromFactory; }
/// <summary> /// Add your user information to the MiCake, which will be tracked automatically. /// </summary> /// <param name="builder"><see cref="IMiCakeBuilder"/></param> /// <param name="miCakeUserType"><see cref="IMiCakeUser{TKey}"/></param> /// <returns></returns> public static IMiCakeBuilder AddIdentityCore(this IMiCakeBuilder builder, Type miCakeUserType) { CheckValue.NotNull(miCakeUserType, nameof(miCakeUserType)); if (!typeof(IMiCakeUser).IsAssignableFrom(miCakeUserType)) { throw new ArgumentException($"Wrong user type,must use {nameof(IMiCakeUser)} to register your micake user."); } builder.ConfigureApplication((app, services) => { //Add identity module. app.ModuleManager.AddMiCakeModule(typeof(MiCakeIdentityModule)); //Early registration IdentityAuditProvider. var userKeyType = TypeHelper.GetGenericArguments(miCakeUserType, typeof(IMiCakeUser <>)); if (userKeyType == null || userKeyType[0] == null) { throw new ArgumentException($"Can not get the primary key type of IMiCakeUser,Please check your config when AddIdentity()."); } var auditProviderType = typeof(IdentityAuditProvider <>).MakeGenericType(userKeyType[0]); services.AddScoped(typeof(IAuditProvider), auditProviderType); }); return(builder); }
/// <summary> /// Converts given string to a byte array using the given <paramref name="encoding"/> /// </summary> public static byte[] GetBytes(this string str, Encoding encoding) { CheckValue.NotNull(str, nameof(str)); CheckValue.NotNull(encoding, nameof(encoding)); return(encoding.GetBytes(str)); }
/// <summary> /// Add the property information required for the persistence object /// </summary> public virtual StoreProperty AddProperty(string name, MemberInfo memberInfo) { CheckValue.NotNull(name, nameof(name)); CheckValue.NotNull(memberInfo, nameof(memberInfo)); // Currently, only property configuration is supported. // If memberinfo is a field type, an error will also be prompted if (memberInfo.MemberType != MemberTypes.Property) { throw new InvalidOperationException($"The {nameof(AddProperty)} method only property is supported," + $" but the parameter '{nameof(memberInfo)}' type is {memberInfo.MemberType}."); } var propertyType = memberInfo.GetMemberType(); var property = new StoreProperty(name, propertyType, memberInfo as PropertyInfo, memberInfo as FieldInfo, memberInfo, this); _properties.Add(name, property); return(property); }
public InternalStoreEntityBuilder(StoreEntityType storeEntity) { CheckValue.NotNull(storeEntity, nameof(storeEntity)); Metadata = storeEntity; _clrType = storeEntity.ClrType; }
public IConventionStoreEntityBuilder AddQueryFilter(LambdaExpression expression) { CheckValue.NotNull(expression, nameof(expression)); Metadata.AddQueryFilter(expression); return(this); }
/// <summary> /// Add the property information required for the persistence object /// </summary> public virtual StorePropertyBuilder Property(string propertyName, MemberInfo clrMemberInfo) { CheckValue.NotNull(propertyName, nameof(propertyName)); CheckValue.NotNull(clrMemberInfo, nameof(clrMemberInfo)); return(new StorePropertyBuilder(_builer.AddProperty(propertyName, clrMemberInfo).Metadata)); }
public virtual void Interpret(IStoreModel storeModel, ModelBuilder receiver) { CheckValue.NotNull(storeModel, nameof(storeModel)); CheckValue.NotNull(receiver, nameof(receiver)); var efEntities = receiver.Model.GetEntityTypes(); var configEntities = storeModel.GetStoreEntities(); foreach (StoreEntityType configEntity in configEntities) { var clrType = configEntity.ClrType; foreach (var efEntity in efEntities) { var efClrType = efEntity.ClrType; if (clrType.IsAssignableFrom(efClrType) || TypeHelper.IsImplementedGenericInterface(efClrType, clrType)) { foreach (var configStrategy in _options.Strategies) { configStrategy.Config(receiver, configEntity, efClrType); } } } } }
/// <summary> /// Created handler descriptors according to <see cref="IServiceProvider"/> and <see cref="IMiCakeHandler"/> to be created /// </summary> /// <param name="serviceProvider">The <see cref="IServiceProvider"/> who is the container for <see cref="IMiCakeHandler"/></param> /// <param name="handlers">all <see cref="IMiCakeHandler"/></param> /// <returns>All handlers descriptor</returns> public static List <MiCakeHandlerDescriptor> CreateHandlerDescriptors(IServiceProvider serviceProvider, IEnumerable <IMiCakeHandler> handlers) { CheckValue.NotNull(serviceProvider, nameof(serviceProvider)); var result = new List <MiCakeHandlerDescriptor>(); if (handlers.Count() == 0) { return(result); } foreach (var handler in handlers) { if (handler is IMiCakeHandlerFactory handlerFactory) { var handlerInstance = handlerFactory.CreateInstance(serviceProvider); if (handlerInstance != null) { result.Add(new MiCakeHandlerDescriptor(handlerInstance, true)); } } else { result.Add(new MiCakeHandlerDescriptor(handler)); } } return(result); }
public Task <TransportMessage> SerializeAsync(Message message, CancellationToken cancellationToken = default) { CheckValue.NotNull(message, nameof(message)); var jsonBody = JsonSerializer.Serialize(message.Body); return(Task.FromResult(new TransportMessage(message.Headers, Encoding.UTF8.GetBytes(jsonBody)))); }
public Task <Message> DeserializeAsync(TransportMessage transportMessage, CancellationToken cancellationToken = default) { CheckValue.NotNull(transportMessage, nameof(transportMessage)); var bodyObject = JsonSerializer.Deserialize <object>(Encoding.UTF8.GetString(transportMessage.Body)); return(Task.FromResult(new Message(transportMessage.Headers, bodyObject))); }
public DefaultDomainObjectModelProvider( IMiCakeModuleContext moduleContext) { CheckValue.NotNull(moduleContext, nameof(moduleContext)); _exceptedModules = moduleContext.MiCakeModules.Where(s => !s.Instance.IsFrameworkLevel) .ToMiCakeModuleCollection(); }
public UserRole(Guid userId, string roleName) { CheckValue.NotNull(userId, nameof(userId)); CheckValue.NotNullOrWhiteSpace(roleName, nameof(roleName)); UserId = userId; RoleName = roleName; }
public EFCoreTransactionObject(IDbContextTransaction dbContextTransaction) { CheckValue.NotNull(dbContextTransaction, nameof(dbContextTransaction)); ID = Guid.NewGuid(); TransactionType = dbContextTransaction.GetType(); _efCoreTransaction = dbContextTransaction; }
/// <summary> /// This is an internal API not subject to the same compatibility standards as public APIs. /// It may be changed or removed without notice in any release. /// /// Add <see cref="IStoreModelProvider"/> to this configer. /// </summary> public virtual StoreConfig AddModelProvider(IStoreModelProvider storeModelProvider) { CheckValue.NotNull(storeModelProvider, nameof(storeModelProvider)); var key = storeModelProvider.GetType().FullName; _modelProviders.TryAdd(key, storeModelProvider); return(this); }
public RabbitMQMessageSubscribeFactory( IRabbitMQBrokerConnector connector, IMessageSerializer serializer, ILoggerFactory loggerFactory) { CheckValue.NotNull(connector, nameof(connector)); _connector = connector; _serializer = serializer; _loggerFactory = loggerFactory; }
/// <summary> /// Gets a substring of a string from beginning of the string. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception> public static string Left(this string str, int len) { CheckValue.NotNull(str, nameof(str)); if (str.Length < len) { throw new ArgumentException("len argument can not be bigger than given string's length!"); } return(str.Substring(0, len)); }
/// <summary> /// Adds a char to beginning of given string if it does not starts with the char. /// </summary> public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType = StringComparison.Ordinal) { CheckValue.NotNull(str, nameof(str)); if (str.StartsWith(c.ToString(), comparisonType)) { return(str); } return(c + str); }
public RabbitMQMessageSubscriber( MessageSubscriberOptions options, IRabbitMQBrokerConnector brokerConnector, IMessageSerializer serializer, ILoggerFactory loggerFactory) { CheckValue.NotNull(brokerConnector, nameof(brokerConnector)); _transportReceiver = new RabbitMQTransportReceiver(options, brokerConnector, loggerFactory); _serializer = serializer; _logger = loggerFactory.CreateLogger <RabbitMQMessageSubscriber>(); }
private LambdaExpression ConvertToEFCoreFilter(LambdaExpression originalExpression, Type efClrType) { CheckValue.NotNull(originalExpression, nameof(originalExpression)); CheckValue.NotNull(efClrType, nameof(efClrType)); var resultType = typeof(Func <,>).MakeGenericType(efClrType, typeof(bool)); var parameter = Expression.Parameter(efClrType); var body = originalExpression.Body.Replace(originalExpression.Parameters[0], parameter); return(Expression.Lambda(resultType, body, parameter)); }
/// <summary> /// Adds an item to the collection if it's not already in the collection. /// </summary> /// <param name="source">The collection</param> /// <param name="item">Item to CheckValue and add</param> /// <typeparam name="T">Type of the items in the collection</typeparam> /// <returns>Returns True if added, returns False if not.</returns> public static bool AddIfNotContains <T>(this ICollection <T> source, T item) { CheckValue.NotNull(source, nameof(source)); if (source.Contains(item)) { return(false); } source.Add(item); return(true); }
private DbContext CheckContextAndGetDbContext(CreateTransactionContext context) { CheckValue.NotNull(context.CurrentUnitOfWork, nameof(context.CurrentUnitOfWork)); CheckValue.NotNull(context.CurrentDbExecutor, nameof(context.CurrentDbExecutor)); var efDbExecutor = context.CurrentDbExecutor as IEFCoreDbExecutor ?? throw new ArgumentException($"Current DbExecutor can not assignable from {nameof(IEFCoreDbExecutor)}"); CheckValue.NotNull(efDbExecutor.EFCoreDbContext, nameof(efDbExecutor.EFCoreDbContext)); return(efDbExecutor.EFCoreDbContext); }
public IMiCakeHandler CreateInstance(IServiceProvider serviceProvider) { CheckValue.NotNull(serviceProvider, nameof(serviceProvider)); var service = serviceProvider.GetRequiredService(HandlerType); if (service is not IMiCakeHandler handler) { throw new InvalidOperationException($"The service typpe : [{HandlerType.FullName}] is not in IServiceProvider"); } return(handler); }
public StoreEntityType(Type clrType) { CheckValue.NotNull(clrType, nameof(clrType)); _originalType = clrType; Name = clrType.Name; _properties = new Dictionary <string, StoreProperty>(); _ignoredMembers = new List <string>(); _filterExpressions = new List <LambdaExpression>(); Builder = new InternalStoreEntityBuilder(this); }
public static string ReplaceFirst(this string str, string search, string replace, StringComparison comparisonType = StringComparison.Ordinal) { CheckValue.NotNull(str, nameof(str)); var pos = str.IndexOf(search, comparisonType); if (pos < 0) { return(str); } return(str.Substring(0, pos) + replace + str.Substring(pos + search.Length)); }
/// <summary> /// Add the property information required for the persistence object /// </summary> public virtual StoreProperty AddProperty(string name) { CheckValue.NotNull(name, nameof(name)); var clrMember = _originalType.GetMembersInHierarchy(name).FirstOrDefault(); if (clrMember == null) { throw new InvalidOperationException($"The property '{name}' cannot be added to the type '{_originalType.Name}' " + $"because there was no property type specified and there is no corresponding CLR property or field."); } return AddProperty(name, clrMember); }
/// <summary> /// Gets the propertyInfo marked by the specified attribute in a class type. /// </summary> /// <param name="classType">class type to find</param> /// <param name="attributeType">attribute</param> /// <returns>some properties info who is marked by the specified attribute</returns> public static IEnumerable <PropertyInfo> GetHasAttributeProperties(Type classType, Type attributeType) { CheckValue.NotNull(classType, nameof(classType)); CheckValue.NotNull(attributeType, nameof(attributeType)); foreach (var property in classType.GetProperties()) { if (property.GetCustomAttribute(attributeType) != null) { yield return(property); } } }
/// <summary> /// Cancel the subscriber's listening and remove it from the dictionary so that GC can reclaim the resources it occupies /// </summary> public async Task RemoveAsync(IMessageSubscriber messageSubscriber) { CheckValue.NotNull(messageSubscriber, nameof(messageSubscriber)); //if no result,return completed directly. if (!_subscriberDic.TryGetValue(messageSubscriber, out _)) { await messageSubscriber.DisposeAsync(); } _subscriberDic.TryRemove(messageSubscriber, out _); await messageSubscriber.DisposeAsync(); }