public static async ValueTask <TReturn> Select <TSource, TReturn>(this ValueTask <TSource> task, Func <TSource, TReturn> selector) { selector.NotNull(nameof(selector)); var result = await task; return(selector(result)); }
public static T ValidateOrDefault <T, TException>(this T current, Func <T> defaultFactory, Func <T, bool> validationFactory, bool throwIfDefaultInvalid = true) where TException : Exception { defaultFactory.NotNull(nameof(defaultFactory)); validationFactory.NotNull(nameof(validationFactory)); T @default; try { if (validationFactory.Invoke(current)) { return(current); } @default = defaultFactory.Invoke(); } catch (TException) { @default = defaultFactory.Invoke(); } if (throwIfDefaultInvalid && !validationFactory.Invoke(@default)) { throw new ArgumentException(InternalResource.ArgumentExceptionDefaultValue); } return(@default); }
public virtual string ToString(Func <TreeingNode <T, TId>, string> toStringFactory) { if (Children.IsEmpty()) { return(string.Empty); } toStringFactory.NotNull(nameof(toStringFactory)); var sb = new StringBuilder(); // Current Node sb.Append(toStringFactory.Invoke(this)); sb.Append(';'); // Children Nodes int i = 0; foreach (var child in Children) { // 链式转换可能存在的子孙节点 sb.Append(child.ToString(toStringFactory)); if (i != Children.Count - 1) { sb.Append(';'); } i++; } return(sb.ToString()); }
public virtual async Task <bool> ChangeConnectionStringAsync (Func <ITenant, string> changeFunc, CancellationToken cancellationToken = default) { changeFunc.NotNull(nameof(changeFunc)); if (Dependency.Options.Stores.UseDataTenant) { await TrySwitchTenantAsync(cancellationToken).ConfigureAwait(); } return(await cancellationToken.RunOrCancelAsync(async() => { var connectionString = changeFunc.Invoke(CurrentTenant); var isChanged = await EnsureDatabaseChangedAsync(connectionString, cancellationToken).ConfigureAwait(); // 实时迁移 if (!IsFromMigrateInvoke) { await MigrateAsync(cancellationToken).ConfigureAwait(); } return isChanged; }) .ConfigureAwait()); }
/// <summary> /// 开启事务 如果成功提交事务,失败回滚事务 /// </summary> /// <param name="func"></param> /// <returns>返回操作结果</returns> public static OperationResponse UseTran(this IUnitOfWork unitOfWork, Func <OperationResponse> func) { func.NotNull(nameof(func)); OperationResponse result = new OperationResponse(); if (unitOfWork.HasCommit()) { result.Type = OperationResponseType.NoChanged; result.Message = "事务已提交!!"; return(result); } try { unitOfWork.BeginTransaction(); result = func.Invoke(); unitOfWork.Commit(); return(result); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); return(new OperationResponse() { Type = OperationResponseType.Error, Message = ex.Message, }); } }
Frame Rebuild(Frame frame) { Func <bool, Frame> old = frame.Done; frame.Done = dropped => { if (old.NotNull()) { this.Receive(old(dropped)); } Frame result = null; lock (this.Lock) { this.activeCount--; if (this.activeCount < this.MaximumActive && this.last.NotNull()) { result = this.Rebuild(this.last); this.activeCount++; this.discardedCount = 0; this.last = null; } } return(result); }; return(frame); }
/// <summary> /// 返回一组不不重复的 IEnumerable<T> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <param name="predicate">自定义重复断言, 不带此参数用dic的key直接对比元素</param> /// <returns></returns> public static IEnumerable <T> NoRepeat <T>(this IEnumerable <T> self, Func <T, T, bool> predicate = null) { if (self.HasItem() && predicate.IsNull()) { // 没有对比断言 用字典key实现对比 Dictionary <T, int> temp_dic = new Dictionary <T, int>(); foreach (var item in self) { if (!temp_dic.ContainsKey(item)) { temp_dic.Add(item, 1); yield return(item); } } } else if (self.HasItem() && predicate.NotNull()) { foreach (var(k, v) in self.ForIndex()) { foreach (var(rk, rv) in self.ReverseForIndex()) { if (k != rk && !predicate(v, rv))//排除自身,不相等返回 { yield return(v); } } } } }
/// <summary> /// 装饰指定的 <paramref name="serviceType"/> /// 使用 <paramref name="decorator"/> 函数. /// </summary> /// <param name="services">要添加到的服务.</param> /// <param name="serviceType">装修服务类型.</param> /// <param name="decorator">装饰函数.</param> /// <exception cref="ArgumentNullException">如果 <paramref name="services"/>, /// <paramref name="serviceType"/>或<paramref name="decorator"/> 参数为 <c>空</c>.</exception> public static bool TryDecorate(this IServiceCollection services, Type serviceType, Func <object, object> decorator) { services.NotNull(nameof(services)); serviceType.NotNull(nameof(serviceType)); decorator.NotNull(nameof(decorator)); return(services.TryDecorateDescriptors(serviceType, out _, x => x.Decorate(decorator))); }
/// <inheritdoc/> public IConvertRegistration <TSource, TTarget> RegisterCreateToOneHistWithCondition <TSourceValue, TTargetValue, TReverseRelation, TTemporalData, TConvertIntention>( Func <TSource, TTarget, IEnumerable <TSourceValue> > sourceFunc, Expression <Func <TTarget, ICollection <TTargetValue> > > targetExpression, Func <TSource, TTarget, bool> toOneHistCriteria, Func <TSource, TTarget, DateTime> toOneReferenceDate, ICreateConvertHelper <TSourceValue, TTargetValue, TReverseRelation, TConvertIntention> createConvertHelper) where TSourceValue : class, TTemporalData where TTargetValue : class, TTemporalData where TReverseRelation : class where TTemporalData : class where TConvertIntention : IBaseConvertIntention { sourceFunc.NotNull(nameof(sourceFunc)); targetExpression.NotNull(nameof(targetExpression)); toOneHistCriteria.NotNull(nameof(toOneHistCriteria)); toOneReferenceDate.NotNull(nameof(toOneReferenceDate)); var operation = this.serviceLocator .GetInstance <IOperationCreateToOneHistWithCondition <TSource, TTarget, TSourceValue, TTargetValue, TReverseRelation, TTemporalData, TConvertIntention> >(); operation.Initialize( sourceFunc, targetExpression, toOneHistCriteria, toOneReferenceDate, createConvertHelper); this.convertHelperOperationWorkUnits.Add(operation); return(this); }
/// <summary> /// 循环集合的每一项,调用委托生成字符串,返回合并后的字符串。默认分隔符为逗号 /// </summary> /// <param name="collection">待处理的集合</param> /// <param name="itemFormatFunc">单个集合项的转换委托</param> /// <param name="separator">分隔符,默认为逗号</param> /// <typeparam name="T">泛型类型</typeparam> /// <returns></returns> public static string ExpandAndToString <T>(this IEnumerable <T> collection, Func <T, string> itemFormatFunc, string separator = ",") { collection = collection as IList <T> ?? collection.ToList(); itemFormatFunc.NotNull(nameof(itemFormatFunc)); if (!collection.Any()) { return(string.Empty); } var sb = new StringBuilder(); var i = 0; var count = collection.Count(); foreach (var t in collection) { if (i == count - 1) { sb.Append(itemFormatFunc(t)); } else { sb.Append(itemFormatFunc(t) + separator); } i++; } return(sb.ToString()); }
public EqualityComparerWrapper(Func <T, T, bool> equality, Func <T, int> getHashCode = null) { equality.NotNull(nameof(equality)); this.equality = equality; this.getHashCode = getHashCode ?? (value => value.GetHashCode()); }
/// <summary> /// Initializes a new instance of the <see cref="SvnInfo"/> class. /// </summary> /// <param name="environment">The Cake environment.</param> /// <param name="clientFactoryMethod">Method to use to initialize a Subversion client.</param> public SvnInfo(ICakeEnvironment environment, Func <ISvnClient> clientFactoryMethod) : base(clientFactoryMethod) { environment.NotNull(nameof(environment)); clientFactoryMethod.NotNull(nameof(clientFactoryMethod)); _environment = environment; }
/// <inheritdoc/> public IConvertRegistration <TSource, TTarget> RegisterCreateToOneWithRelation <TSourceValue, TTargetValue, TRelation, TConvertIntention>( Func <TSource, TTarget, TSourceValue> sourceFunc, Expression <Func <TTarget, TTargetValue> > targetExpression, Func <TSource, TTarget, TRelation> relationFunc, ICreateConvertHelper <TSourceValue, TTargetValue, TRelation, TConvertIntention> createConvertHelper) where TSourceValue : class where TTargetValue : class where TRelation : class where TConvertIntention : IBaseConvertIntention { sourceFunc.NotNull(nameof(sourceFunc)); targetExpression.NotNull(nameof(targetExpression)); relationFunc.NotNull(nameof(relationFunc)); var operation = this.serviceLocator .GetInstance <IOperationCreateToOneWithRelationInclTargetArg <TSource, TTarget, TSourceValue, TTargetValue, TRelation, TConvertIntention> >(); operation.Initialize( sourceFunc, targetExpression, relationFunc, createConvertHelper); this.convertHelperOperationWorkUnits.Add(operation); return(this); }
/// <inheritdoc/> public IConvertRegistration <TSource, TTarget> RegisterMergeLevel <TSourceValue, TTargetValue, TMergeValue, TConvertIntention>( Func <TSource, IEnumerable <TMergeValue> > mergeFunc, Func <TMergeValue, IEnumerable <TSourceValue> > sourceFunc, Expression <Func <TTarget, ICollection <TTargetValue> > > targetExpression, ICreateConvertHelper <TSourceValue, TTargetValue, TTarget, TConvertIntention> createConvertHelper) where TSourceValue : class where TTargetValue : class where TMergeValue : class where TConvertIntention : IBaseConvertIntention { mergeFunc.NotNull(nameof(mergeFunc)); sourceFunc.NotNull(nameof(sourceFunc)); targetExpression.NotNull(nameof(targetExpression)); createConvertHelper.NotNull(nameof(createConvertHelper)); var operation = this.serviceLocator .GetInstance <IOperationMergeLevel <TSource, TTarget, TSourceValue, TTargetValue, TMergeValue, TConvertIntention> >(); operation.Initialize( mergeFunc, sourceFunc, targetExpression, createConvertHelper); this.convertHelperOperationWorkUnits.Add(operation); return(this); }
/// <summary> ///装饰所有类型的注册服务 <typeparamref name="TService"/> /// 使用 <paramref name="decorator"/> 函数. /// </summary> /// <typeparam name="TService">装修服务类型.</typeparam> /// <param name="services">要添加到的服务.</param> /// <param name="decorator">装饰函数.</param> /// <exception cref="MissingTypeRegistrationException">如果没有服务<typeparamref name="TService"/>已注册.</exception> /// <exception cref="ArgumentNullException">如果 <paramref name="services"/> ///或<paramref name="decorator"/> 参数为 <c>空</c>.</exception> public static IServiceCollection Decorate <TService>(this IServiceCollection services, Func <TService, IServiceProvider, TService> decorator) { services.NotNull(nameof(services)); decorator.NotNull(nameof(decorator)); return(services.DecorateDescriptors(typeof(TService), x => x.Decorate(decorator))); }
public Func <Key, ValueTask <T> > CreateIndexMany <Key>(Func <T, IEnumerable <Key> > keySelector) { keySelector.NotNull(nameof(keySelector)); var index = new AtomicDictionary <Key, T>(); _upserters.Add(async transaction => { foreach (var key in keySelector(transaction.Item)) { index[key] = transaction.Item; } }); _deleters.Add(async item => { foreach (var key in keySelector(item)) { index.TryRemove(key); } }); return(async key => { await Initialize(); return index.TryGetValue(key, out var item) ? item : default; }); }
/// <summary> /// 开启事务 如果成功提交事务,失败回滚事务 /// </summary> /// <param name="func">要执行的操作</param> /// <returns></returns> public OperationResponse UseTran(Func <OperationResponse> func) { func.NotNull(nameof(func)); OperationResponse result = new OperationResponse(); if (HasCommitted) { result.Type = OperationEnumType.NoChanged; result.Message = "事务已提交!!"; return(result); } try { this.BeginTransaction(); result = func.Invoke(); this.Commit(); return(result); } catch (Exception ex) { this.Rollback(); _logger.LogError(ex.Message, ex); return(new OperationResponse() { Type = OperationEnumType.Error, Message = ex.Message, }); } }
/// <summary> /// Initializes a new instance of the <see cref="FileLinkOptionalSettingsBuilder"/> class. /// </summary> /// <param name="builder">Callback called for building the file link.</param> internal FileLinkOptionalSettingsBuilder(Func <IIssue, IDictionary <string, string>, Uri> builder) : base(builder) { builder.NotNull(nameof(builder)); this.builder = builder; }
/// <summary> /// Sets the subscriber repository factory /// </summary> /// <remarks>USE THIS ONLY UNIT TESTING</remarks> /// <param name="subscriberRepositoryFactory">The factory</param> internal void SetSubscriberRepositoryFactory( Func <AclConfiguration, HttpRequestMessage, ISubscriberRepository> subscriberRepositoryFactory) { subscriberRepositoryFactory.NotNull(nameof(subscriberRepositoryFactory)); _subscriberRepositoryFactory = subscriberRepositoryFactory; }
protected IActionResult HandleResponse <T>(OperationResult <T> result, Func <CreatedAtRouteResult> createdAt = null) { switch (result.Status) { case EnumOperationResult.Ok: return(Ok(result.Entity)); case EnumOperationResult.Added: if (createdAt.NotNull()) { return(createdAt()); } return(Created("", result.Entity)); case EnumOperationResult.Updated: return(Ok(result.Entity)); case EnumOperationResult.Accepted: return(Accepted(result.Entity)); case EnumOperationResult.NotFound: return(NotFound()); case EnumOperationResult.Duplicate: return(StatusCode(StatusCodes.Status409Conflict, result.Entity)); case EnumOperationResult.Error: return(BadRequest(result.Errors)); } return(Unauthorized()); }
/// <summary> /// 装饰指定的 <paramref name="serviceType"/> /// 使用 <paramref name="decorator"/> 函数. /// </summary> /// <param name="services">要添加到的服务.</param> /// <param name="serviceType">装修服务类型.</param> /// <param name="decorator">装饰函数.</param> /// <exception cref="MissingTypeRegistrationException">如果没有指定的服务 <paramref name="serviceType"/> 已注册.</exception> /// <exception cref="ArgumentNullException">如果 <paramref name="services"/>, /// <paramref name="serviceType"/>或<paramref name="decorator"/> 参数为 <c>空</c>.</exception> public static IServiceCollection Decorate(this IServiceCollection services, Type serviceType, Func <object, IServiceProvider, object> decorator) { services.NotNull(nameof(services)); serviceType.NotNull(nameof(serviceType)); decorator.NotNull(nameof(decorator)); return(services.DecorateDescriptors(serviceType, x => x.Decorate(decorator))); }
public IEnumerable <T> ConsumeWhile(Func <T, bool> conditional) { conditional.NotNull(nameof(conditional)); while (TryConsumeIf(out var item, conditional)) { yield return(item); } }
/// <summary> /// Constructor /// </summary> /// <param name="expression">Expression that must return true in order to fulfill this specification</param> /// <param name="exceptioToThrow">Exception to be thrown when entity does not fulfill the business rule</param> public ExpressionSpecification( Func <TEntity, bool> expression, Func <TEntity, Exception> exceptioToThrow) : base(exceptioToThrow) { expression.NotNull(nameof(expression)); _expression = expression; }
/// <summary> /// Executes <c>evaluator</c> if <c>o</c> is not null and returns result of evaluation. /// Otherwise <c>failureValue</c> is returned. /// </summary> public static TResult ReturnN <TInput, TResult>( this TInput?o, Func <TInput, TResult> evaluator, TResult failureValue = default(TResult)) where TInput : struct { evaluator.NotNull(); return(o == null ? failureValue : evaluator(o.Value)); }
/// <summary> /// Executes <c>evaluator</c> if <c>o</c> is not null and returns result of evaluation. /// Otherwise <c>failureValue</c> is returned. /// </summary> public static TResult Return <TInput, TResult>( this TInput o, Func <TInput, TResult> evaluator, TResult failureValue = default(TResult)) where TInput : class { evaluator.NotNull(); return(o == null ? failureValue : evaluator(o)); }
/// <summary> /// Executes <c>evaluator</c> if <c>o</c> is not null and returns result of evaluation. /// Otherwise <c>null</c> is returned. /// </summary> public static TResult WithN <TInput, TResult>(this TInput?o, Func <TInput, TResult> evaluator) where TResult : class where TInput : struct { evaluator.NotNull(); return(o == null ? null : evaluator(o.Value)); }
/// <summary> /// 装饰所有类型的注册服务e <typeparamref name="TService"/> /// 使用 <paramref name="decorator"/> 函数. /// </summary> /// <typeparam name="TService">装修服务类型.</typeparam> /// <param name="services">要添加到的服务.</param> /// <param name="decorator">装饰函数.</param> /// <exception cref="ArgumentNullException">如果 <paramref name="services"/> ///或<paramref name="decorator"/> 参数为 <c>空</c>.</exception> public static bool TryDecorate <TService>(this IServiceCollection services, Func <TService, TService> decorator) { services.NotNull(nameof(services)); decorator.NotNull(nameof(decorator)); return(services.TryDecorateDescriptors(typeof(TService), out _, x => x.Decorate(decorator))); }
public static IEnumerable <T> DistinctBy <T, TKey>(this IEnumerable <T> sourceCollection, Func <T, TKey> keySelector, IEqualityComparer <TKey> comparer = null) { sourceCollection.NotNull(); keySelector.NotNull(); return(sourceCollection.DistinctBySelector(keySelector, comparer)); }
/// <summary> /// Initializes a new instance of the <see cref="HtmlDxDataGridColumnDescription"/> class. /// </summary> /// <param name="id">Id of the column.</param> /// <param name="valueRetriever">Function for retrieving the value of the column.</param> public HtmlDxDataGridColumnDescription(string id, Func <IIssue, object> valueRetriever) { id.NotNullOrWhiteSpace(nameof(id)); valueRetriever.NotNull(nameof(valueRetriever)); this.Id = id; this.ValueRetriever = valueRetriever; }
/// <summary> /// Executes <c>evaluator</c> if <c>o</c> is not null and returns result of evaluation. /// Otherwise <c>null</c> is returned. /// </summary> public static TResult With <TInput, TResult>(this TInput o, Func <TInput, TResult> evaluator) where TResult : class where TInput : class { evaluator.NotNull(); return(o == null ? null : evaluator(o)); }
/// <summary> /// Constructor /// </summary> /// <param name="jobType">The type of the class that implements the job</param> /// <param name="builder">The trigger builder</param> public JobConfiguration( Type jobType, Func<TriggerBuilder> builder) { jobType.Is<IJob>(); builder.NotNull(nameof(builder)); JobType = jobType; TriggerBuilder = builder; }
/// <summary> /// Returns the list of all the assemblies that have been loaded /// into the execution context of appDomain that fulfill the predicate /// </summary> /// <param name="appDomain">The app domain</param> /// <param name="predicate">Predicate</param> /// <returns>The list of all assemblyes already loaded into the execution context of app domain that fulfill the predicate</returns> public static IEnumerable<Assembly> GetAssemblies( this AppDomain appDomain, Func<Assembly, bool> predicate) { appDomain.NotNull(nameof(appDomain)); predicate.NotNull(nameof(predicate)); return appDomain .GetAssemblies() .Where(predicate) .ToList(); }
/// <summary> /// Register the ACL cache provider /// (in case it differs from the cache for the rest of the application) /// </summary> /// <param name="provider"></param> public void RegisterAclCacheProvider(Func<ICache> provider) { provider.NotNull(nameof(provider)); _config.Properties.GetOrAdd(typeof(ICache), obj => provider); }
/// <summary> /// Sets the now factory /// </summary> /// <param name="nowFactory">The factory</param> /// <remarks>USE THIS ONLY FOR UNIT TESTING</remarks> internal void SetNowFactory(Func<DateTime> nowFactory) { nowFactory.NotNull(nameof(nowFactory)); _nowFactory = nowFactory; }
/// <summary> /// Sets the resolver factory /// </summary> /// <remarks>USE THIS ONLY FOR UNIT TESTING</remarks> /// <param name="resolverFactory">The factory</param> internal void SetResolverFactory(Func<HttpRequestMessage, Type, object> resolverFactory) { resolverFactory.NotNull(nameof(resolverFactory)); _resolverFactory = resolverFactory; }
/// <summary> /// Sets the subscriber repository factory /// </summary> /// <remarks>USE THIS ONLY UNIT TESTING</remarks> /// <param name="subscriberRepositoryFactory">The factory</param> internal void SetSubscriberRepositoryFactory( Func<AclConfiguration, HttpRequestMessage, ISubscriberRepository> subscriberRepositoryFactory) { subscriberRepositoryFactory.NotNull(nameof(subscriberRepositoryFactory)); _subscriberRepositoryFactory = subscriberRepositoryFactory; }
/// <summary> /// Sets the DateTime Now factory /// </summary> /// <param name="dateTimeNowFactory">The factory</param> /// <remarks>USE THIS ONLY FOR UNIT TESTING</remarks> internal void SetDateTimeNowFactory(Func<DateTime> dateTimeNowFactory) { dateTimeNowFactory.NotNull(nameof(dateTimeNowFactory)); _dateTimeNowFactory = dateTimeNowFactory; }
/// <summary> /// Sets the security token handler factory /// </summary> /// <param name="securityTokenHandlerFactory">The factory</param> /// <remarks>USE THIS ONLY FOR UNIT TESTING</remarks> internal void SetSecurityTokenHandlerFactory(Func<JwtSecurityTokenHandler> securityTokenHandlerFactory) { securityTokenHandlerFactory.NotNull(nameof(securityTokenHandlerFactory)); _securityTokenHandlerFactory = securityTokenHandlerFactory; }
/// <summary> /// Sets the CORS engine factory /// </summary> /// <param name="corsEngineFactory">The factory</param> /// <remarks>USE THIS ONLY FOR UNIT TESTING</remarks> internal void SetCorsEngineFactory(Func<CorsEngine> corsEngineFactory) { corsEngineFactory.NotNull(nameof(corsEngineFactory)); _corsEngineFactory = corsEngineFactory; }