コード例 #1
0
        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);
        }
コード例 #2
0
        /// <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);
        }
コード例 #3
0
        public MiCakeHandlerDescriptor(IMiCakeHandler handler, bool isFromFactory = false)
        {
            CheckValue.NotNull(handler, nameof(handler));

            Handler       = handler;
            IsFromFactory = IsFromFactory;
        }
コード例 #4
0
        /// <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);
        }
コード例 #5
0
ファイル: StringExtensions.cs プロジェクト: qkb/MiCake
        /// <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));
        }
コード例 #6
0
ファイル: StoreEntityType.cs プロジェクト: wrsxinlang/MiCake
        /// <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);
        }
コード例 #7
0
        public InternalStoreEntityBuilder(StoreEntityType storeEntity)
        {
            CheckValue.NotNull(storeEntity, nameof(storeEntity));

            Metadata = storeEntity;
            _clrType = storeEntity.ClrType;
        }
コード例 #8
0
        public IConventionStoreEntityBuilder AddQueryFilter(LambdaExpression expression)
        {
            CheckValue.NotNull(expression, nameof(expression));
            Metadata.AddQueryFilter(expression);

            return(this);
        }
コード例 #9
0
        /// <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));
        }
コード例 #10
0
        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);
                        }
                    }
                }
            }
        }
コード例 #11
0
        /// <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);
        }
コード例 #12
0
        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))));
        }
コード例 #13
0
        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)));
        }
コード例 #14
0
        public DefaultDomainObjectModelProvider(
            IMiCakeModuleContext moduleContext)
        {
            CheckValue.NotNull(moduleContext, nameof(moduleContext));

            _exceptedModules = moduleContext.MiCakeModules.Where(s => !s.Instance.IsFrameworkLevel)
                               .ToMiCakeModuleCollection();
        }
コード例 #15
0
        public UserRole(Guid userId, string roleName)
        {
            CheckValue.NotNull(userId, nameof(userId));
            CheckValue.NotNullOrWhiteSpace(roleName, nameof(roleName));

            UserId   = userId;
            RoleName = roleName;
        }
コード例 #16
0
        public EFCoreTransactionObject(IDbContextTransaction dbContextTransaction)
        {
            CheckValue.NotNull(dbContextTransaction, nameof(dbContextTransaction));

            ID = Guid.NewGuid();
            TransactionType = dbContextTransaction.GetType();

            _efCoreTransaction = dbContextTransaction;
        }
コード例 #17
0
ファイル: StoreConfig.cs プロジェクト: wrsxinlang/MiCake
        /// <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);
        }
コード例 #18
0
        public RabbitMQMessageSubscribeFactory(
            IRabbitMQBrokerConnector connector,
            IMessageSerializer serializer,
            ILoggerFactory loggerFactory)
        {
            CheckValue.NotNull(connector, nameof(connector));

            _connector     = connector;
            _serializer    = serializer;
            _loggerFactory = loggerFactory;
        }
コード例 #19
0
ファイル: StringExtensions.cs プロジェクト: qkb/MiCake
        /// <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));
        }
コード例 #20
0
ファイル: StringExtensions.cs プロジェクト: qkb/MiCake
        /// <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);
        }
コード例 #21
0
 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>();
 }
コード例 #22
0
        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));
        }
コード例 #23
0
        /// <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);
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        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);
        }
コード例 #26
0
ファイル: StoreEntityType.cs プロジェクト: wrsxinlang/MiCake
        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);
        }
コード例 #27
0
ファイル: StringExtensions.cs プロジェクト: qkb/MiCake
        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));
        }
コード例 #28
0
ファイル: StoreEntityType.cs プロジェクト: MiCake/MiCake
        /// <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);
        }
コード例 #29
0
ファイル: ReflectionHelper.cs プロジェクト: wrsxinlang/MiCake
        /// <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);
                }
            }
        }
コード例 #30
0
        /// <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();
        }