public static TValue SafeGet <TKey, TValue>(this IEnumerable <KeyValuePair <TKey, TValue> > values, TKey key, Func <TValue> defaultValue = null) { if (values.IsNullOrEmpty()) { return(defaultValue.IsNull() ? default(TValue) : defaultValue()); } var dictionary = values.ToDictionary(x => x.Key, x => x.Value); return(!dictionary.ContainsKey(key) ? defaultValue.IsNull() ? default(TValue) : defaultValue() : dictionary[key]); }
public static TReturn SafeGetAs <TKey, TValue, TReturn>(this IEnumerable <KeyValuePair <TKey, TValue> > values, TKey key, Func <TReturn> defaultValue = null, bool ignoreCase = true) { if (values.IsNullOrEmpty()) { return(defaultValue.IsNull() ? default(TReturn) : defaultValue()); } var dictionary = values.ToDictionary(x => x.Key, x => x.Value); return(!dictionary.ContainsKey(key) ? defaultValue.IsNull() ? default(TReturn) : defaultValue() : (TReturn)Convert.ChangeType(dictionary[key], typeof(TReturn))); }
public static void EnsureNotNull <Error>(this string str, Func <Error> errorFunc) where Error : Exception { if (IsNullOrEmpty(str) && !errorFunc.IsNull()) { throw errorFunc(); } }
/// <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); } } } } }
public static IEnumerable <LSBody> RaycastAll(Vector2d start, Vector2d end) { _Version++; LSBody.PrepareAxisCheck(start, end); foreach (FractionalLineAlgorithm.Coordinate coor in GetRelevantNodeCoordinates(start, end)) { int indexX = coor.X; int indexY = coor.Y; if (!Partition.CheckValid(coor.X, coor.Y)) { break; } PartitionNode node = Partition.GetNode(indexX, indexY); for (int i = node.ContainedDynamicObjects.Count - 1; i >= 0; i--) { LSBody body = PhysicsManager.SimObjects[node.ContainedDynamicObjects[i]]; if (body.IsNotNull() && body.RaycastVersion != _Version) { if (Conditional.IsNull() || Conditional()) { body.RaycastVersion = _Version; if (body.Overlaps(bufferIntersectionPoints)) { yield return(body); } } } } } Conditional = null; yield break; }
public async Task <bool> Delete(Func <T, bool> predicate) { if (predicate.IsNull()) { throw new UnableToExecuteQueryException(nameof(predicate), nameof(this.Delete)); } var ct = new CancellationToken(); var state = await this.GetState(); using (var tx = this._stateManager.CreateTransaction()) { var stateEnum = await state.CreateEnumerableAsync(tx); var customers = stateEnum.GetAsyncEnumerator(); while (await customers.MoveNextAsync(ct)) { if (predicate(customers.Current.Value)) { await state.TryRemoveAsync(tx, customers.Current.Value.Id); } } await tx.CommitAsync(); return(true); } }
/// <summary> /// Performs a conversion from one task type to another. /// </summary> /// <typeparam name="TOriginalReturnType"> /// The original task return type. /// </typeparam> /// <typeparam name="TNewReturnType"> /// The new task return type. /// </typeparam> /// <param name="task"> /// The task to execute. /// </param> /// <param name="timeout"> /// A time out period to wait for the task execution. /// </param> /// <param name="convert"> /// The conversion method that performs the conversion. /// </param> /// <returns> /// A new task that will execute the conversion with the original task /// is completed. /// </returns> public static Task <TNewReturnType> AsyncConvert <TOriginalReturnType, TNewReturnType>( this Task <TOriginalReturnType> task, TimeSpan timeout, Func <TOriginalReturnType, TNewReturnType> convert) { if (task.IsNull()) { throw new ArgumentNullException("task"); } if (convert.IsNull()) { throw new ArgumentNullException("convert"); } Task <TNewReturnType> retval = null; try { retval = Help.SafeCreate(() => new Task <TNewReturnType>(() => convert(task.WaitForResult(timeout)))); retval.Start(); return(retval); } catch (Exception) { if (retval.IsNotNull()) { retval.Dispose(); } throw; } }
public static IDataContext CreateDataContext(bool useTransaction = false) { lock (_lock) { if (_createDataContext.IsNull()) { throw new NullReferenceException("DataContextFactory.CreateDataContext is not properly configured."); } if (_currentContext.IsNull()) { return(_createDataContext(useTransaction)); } IDataContext context; _currentContext.TryGetTarget(out context); if (context.IsNotNull() && !context.IsDisposed) { throw new InvalidOperationException("CurrentContext has not been disposed."); } return(_createDataContext(useTransaction)); } }
/// <summary> /// 以异步DTO插入实体 /// </summary> /// <typeparam name="TInputDto">添加DTO类型</typeparam> /// <param name="dto">添加DTO</param> /// <param name="checkFunc">添加信息合法性检查委托</param> /// <param name="insertFunc">由DTO到实体的转换委托</param> /// <returns>操作结果</returns> public virtual async Task <OperationResponse> InsertAsync <TInputDto>(TInputDto dto, Func <TInputDto, Task> checkFunc = null, Func <TInputDto, TEntity, Task <TEntity> > insertFunc = null, Func <TEntity, TInputDto> completeFunc = null) where TInputDto : IInputDto <Tkey> { dto.NotNull(nameof(dto)); try { if (checkFunc.IsNotNull()) { await checkFunc(dto); } TEntity entity = dto.MapTo <TEntity>(); if (!insertFunc.IsNull()) { entity = await insertFunc(dto, entity); } entity = CheckInsert(entity); await _dbSet.AddAsync(entity); if (completeFunc.IsNotNull()) { dto = completeFunc(entity); } int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? ResultMessage.InsertSuccess : ResultMessage.NoChangeInOperation, count > 0 ? OperationEnumType.Success : OperationEnumType.NoChanged)); } catch (SuktAppException e) { return(new OperationResponse(e.Message, OperationEnumType.Error)); } catch (Exception ex) { return(new OperationResponse(ex.Message, OperationEnumType.Error)); } }
/// <summary> /// 添加服务引用(支持服务特征)。 /// </summary> /// <typeparam name="TService">指定的服务类型。</typeparam> /// <typeparam name="TImplementation">指定的实现类型。</typeparam> /// <param name="factory">给定的服务类型对象引用转换为实现实例的工厂方法(可选;默认直接表示为实现实例)。</param> /// <returns>返回 <see cref="IExtensionBuilder"/>。</returns> public virtual IExtensionBuilder AddServiceReference <TService, TImplementation> (Func <object, TImplementation> factory = null) where TImplementation : TService { var implementationType = typeof(TImplementation); // 提前判定此实现服务类型是否已存在 if (!Services.Any(p => p.ServiceType == implementationType)) { var serviceType = typeof(TService); var characteristics = GetServiceCharacteristics(serviceType); if (factory.IsNull()) { factory = obj => (TImplementation)obj; } Services.AddByCharacteristics(implementationType, // 解决可能出现获取指定服务类型对象并表示为实现类型时抛出已存在此服务缓存键的异常 sp => factory.Invoke(sp.GetRequiredService(serviceType)), characteristics); } return(this); }
/// <summary> /// 异步添加单条实体 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual async Task <OperationResponse> InsertAsync(TEntity entity, Func <TEntity, Task> checkFunc = null, Func <TEntity, TEntity, Task <TEntity> > insertFunc = null, Func <TEntity, TEntity> completeFunc = null) { entity.NotNull(nameof(entity)); try { if (checkFunc.IsNotNull()) { await checkFunc(entity); } if (!insertFunc.IsNull()) { entity = await insertFunc(entity, entity); } //entity = CheckInsert(entity); await _dbSet.AddAsync(entity); if (completeFunc.IsNotNull()) { entity = completeFunc(entity); } int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? "添加成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged)); } catch (AppException e) { return(new OperationResponse(e.Message, OperationResponseType.Error)); } catch (Exception ex) { return(new OperationResponse(ex.Message, OperationResponseType.Error)); } }
protected override bool InternalExecute(ProcessExecutingContext context) { var entitySchemaManager = UserConnection.EntitySchemaManager; var parentSchema = entitySchemaManager.GetInstanceByUId(ParentSchemaUId); string parentSchemaName = parentSchema.Name; var parentSchemaColumns = parentSchema.Columns; string parentColumnResultName = parentSchemaColumns.FindByUId(ParentColumnResultUId).Name; var childSchema = entitySchemaManager.GetInstanceByUId(ChildSchemaUId); string childSchemaName = childSchema.Name; var childSchemaColumns = childSchema.Columns; string childColumnName = childSchemaColumns.FindByUId(ChildColumnUId).Name; string parentColumnRelationName = childSchemaColumns.FindByUId(ParentColumnRelationUId).ColumnValueName; Select selectSum = new Select(UserConnection). Column(Func.Sum(childColumnName)). From(childSchemaName). Where(parentColumnRelationName).IsEqual(Column.Parameter(ParentColumnRelationValue.ToString())) as Select; Update updateParent = new Update(UserConnection, parentSchemaName). Set(parentColumnResultName, Func.IsNull(Column.SubSelect(selectSum), Column.Const(0))). Where(childSchema.PrimaryColumn.Name).IsEqual(Column.Parameter(ParentColumnRelationValue.ToString())) as Update; updateParent.Execute(); return(true); }
/// <summary> /// 寻找当前子级层级,但是不递归 /// </summary> /// <param name="currNode"></param> /// <param name="findAction"></param> /// <returns></returns> public BaseLeaf <TKey> FindCurrLevel(TNode currNode, Func <BaseLeaf <TKey>, bool> predicate) { if (predicate.IsNull()) { return(default(TLeaf)); } if (currNode.ChildrenNodes.HasItem()) { foreach (var item in currNode.ChildrenNodes) { if (item is TLeaf) { var l = item; if (predicate(l)) { return(l); } } if (item is TNode) { var n = item as BaseNode <TKey>; if (predicate((BaseLeaf <TKey>)n)) { return((BaseLeaf <TKey>)n); } } } } return(default(TLeaf)); }
/// <summary> /// 重试方法 /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="action">方法</param> /// <param name="numRetries">重试次数</param> /// <param name="retryTimeout">延时多长时间后重试,单位毫秒</param> /// <param name="throwIfFail">经过几轮重试操作后依然发生异常时是否将异常抛出</param> /// <param name="onFailureAction">操作失败执行的方法</param> /// <returns></returns> public static T Retry <T>(this Func <T> action, int numRetries, int retryTimeout, bool throwIfFail, Action onFailureAction) { if (action.IsNull()) { throw new ArgumentNullException("action"); } T retVal = default(T); do { try { retVal = action(); return(retVal); } catch { if (onFailureAction.IsNotNull()) { onFailureAction(); } if (numRetries <= 0 && throwIfFail) { throw; } if (retryTimeout > 0) { Thread.Sleep(retryTimeout); } } } while (numRetries-- > 0); return(retVal); }
/// <summary> /// 以异步DTO更新实体 /// </summary> /// <typeparam name="TInputDto">更新DTO类型</typeparam> /// <param name="dto">更新DTO</param> /// <param name="checkFunc">添加信息合法性检查委托</param> /// <param name="updateFunc">由DTO到实体的转换委托</param> /// <returns>操作结果</returns> public virtual async Task <OperationResponse> UpdateAsync <TInputDto>(TInputDto dto, Func <TInputDto, TEntity, Task> checkFunc = null, Func <TInputDto, TEntity, Task <TEntity> > updateFunc = null) where TInputDto : class, IInputDto <Tkey>, new() { dto.NotNull(nameof(dto)); try { TEntity entity = await this.GetByIdAsync(dto.Id); if (entity.IsNull()) { return(new OperationResponse($"该{dto.Id}键的数据不存在", OperationEnumType.QueryNull)); } if (checkFunc.IsNotNull()) { await checkFunc(dto, entity); } entity = dto.MapTo(entity); if (!updateFunc.IsNull()) { entity = await updateFunc(dto, entity); } entity = CheckUpdate(entity); _dbSet.Update(entity); int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? ResultMessage.UpdateSuccess : ResultMessage.NoChangeInOperation, count > 0 ? OperationEnumType.Success : OperationEnumType.NoChanged)); } catch (SuktAppException e) { return(new OperationResponse(e.Message, OperationEnumType.Error)); } catch (Exception ex) { throw ex; } }
private IsNullQueryFunction GetLczColumnQueryFunction(string lczTableName, string lczTableColumnName, string mainTableName, string mainTableColumnName) { QueryColumnExpression lczTableColumnExpression = Column.SourceColumn(lczTableName, lczTableColumnName); QueryColumnExpression mainTableColumnExpression = Column.SourceColumn(mainTableName, mainTableColumnName); return(Func.IsNull(lczTableColumnExpression, mainTableColumnExpression)); }
public static Document ParseFile(string fileName, string parser, Func <ITableParser, ITableParser> initializer = null) { if (initializer.IsNull()) { return(GetParser(parser).Parse(fileName)); } return(initializer(GetParser(parser)).Parse(fileName)); }
/// <summary> /// Similar to Chain, except checks if the Object or Function is null first and returns the default value if they are /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="Object">Object to run the function on</param> /// <param name="Function">Function to run</param> /// <param name="DefaultValue">Default value to return if the action or object is null</param> /// <returns>The result of the function or the default value</returns> public static R Do <T, R>(this T Object, Func <T, R> Function, R DefaultValue = default(R)) { if (Object.IsNull() || Function.IsNull()) { return(DefaultValue); } return(Object.Chain(Function)); }
/// <summary> /// 字體大小自動變更 /// </summary> /// <param name="graphics"></param> /// <param name="size"></param> /// <param name="font"></param> /// <param name="str"></param> /// <param name="func"></param> /// <returns></returns> public static float NewFontSize(Graphics graphics, Size size, Font font, string str, Func <float, float> func = null) { SizeF stringSize = graphics.MeasureString(str, font); float f = font.Size * Math.Min(size.Height * 0.96f / stringSize.Height, size.Width * 0.9f / stringSize.Width); f = func.IsNull() ? f : func(f); return(f < 0 || float.IsInfinity(f) ? 1f : f); }
/// <summary> /// Configures a converter for the member (property or constructor parameter) specified by the /// provided declaring type and member name. Use this method when you need different members of /// a target type to each use a different converter. If you want all members of a target type to /// use the same converter, use the other <see cref="Add{T}(Type, Func{string, T})"/> method. /// </summary> /// <param name="declaringType">The declaring type of a member that needs a converter.</param> /// <param name="memberName">The name of a member that needs a converter.</param> /// <param name="convertFunc">A function that does the conversion from string to <typeparamref name="T"/>.</param> /// <returns>This instance of <see cref="ValueConverters"/>.</returns> /// <typeparam name="T">The concrete type of the object returned by the <paramref name="convertFunc"/> function.</typeparam> /// <exception cref="ArgumentNullException"> /// If <paramref name="declaringType"/>, <paramref name="memberName"/>, or <paramref name="convertFunc"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If there are no members of <paramref name="declaringType"/> that match <paramref name="memberName"/>, or /// if the <typeparamref name="T"/> type is not assignable to any of the matching members. /// </exception> public ValueConverters Add <T>(Type declaringType, string memberName, Func <string, T> convertFunc) { if (convertFunc.IsNull()) { throw new ArgumentNullException(nameof(convertFunc)); } return(Add(declaringType, memberName, typeof(T), value => convertFunc(value))); }
public static IEnumerable <T> SafeWhere <T>(this IEnumerable <T> values, Func <T, bool> predicate) { if (values.IsNull() || predicate.IsNull()) { return(new List <T>()); } return(values.Where(predicate)); }
public static IEnumerable <TResult> SafeSelect <T, TResult>(this IEnumerable <T> values, Func <T, TResult> selector) { if (values.IsNull() || selector.IsNull()) { return(new List <TResult>()); } return(values.Select(selector)); }
/// <summary> /// Initializes a new instance of the <see cref="Resolver"/> class. /// <para> /// Use this constructor when support for named parameters is required. /// </para> /// </summary> /// <param name="resolve"> /// A delegate that returns a dependency for the specified type. /// </param> /// <param name="resolveNamed"> /// A delegate that returns a dependency for the specified type and parameter name. /// </param> /// <param name="canResolve"> /// A delegate that returns a value indicating whether a dependency can /// be resolved for the specified type. /// </param> /// <param name="canResolveNamed"> /// A delegate that returns a value indicating whether a dependency can /// be resolved for the specified type and parameter name. /// </param> public Resolver(Func <Type, object> resolve, Func <Type, string, object> resolveNamed, Func <Type, bool> canResolve, Func <Type, string, bool> canResolveNamed) { if (resolve.IsNull()) { throw new ArgumentNullException(nameof(resolve)); } if (resolveNamed.IsNull()) { throw new ArgumentNullException(nameof(resolveNamed)); } if (canResolve.IsNull()) { throw new ArgumentNullException(nameof(canResolve)); } if (canResolveNamed.IsNull()) { throw new ArgumentNullException(nameof(canResolveNamed)); } CanResolve = p => { try { if (canResolveNamed(p.ParameterType, p.Name)) { return(true); } } catch { // ignored } try { return(canResolve(p.ParameterType)); } catch { return(false); } }; Resolve = p => { try { var obj = resolveNamed(p.ParameterType, p.Name); if (obj.IsNotNull()) { return(obj); } } catch { // ignored } try { return(resolve(p.ParameterType)); } catch { return(null); } }; }
/// <summary> /// 将结果字符串转换为指定类型函数,当默认转换实现无法转换时使用 /// </summary> /// <param name="action">响应结果转换回调函数,参数为响应结果</param> public TRequest Convert(Func <string, TResult> action) { if (action.IsNull()) { return(This()); } _convertAction = action; return(This()); }
/// <summary> /// Sets the value of the <see cref="Root"/> property to the instance returned by the specified /// callback function. The callback function MUST NOT return null. /// <para>NOTE: This method should only be called at the beginning of an application. Any calls to this method after /// the <see cref="Root"/> property has been accessed (i.e. when <see cref="IsLocked"/> is true) will /// result in an <see cref="InvalidOperationException"/> being thrown.</para> /// </summary> /// <param name="getRoot"> /// A function that returns the instance of <see cref="IConfiguration"/> to be used as the <see cref="Root"/> /// property. This function MUST NOT return null. /// </param> /// <exception cref="ArgumentNullException">If the <paramref name="getRoot"/> parameter is null.</exception> /// <exception cref="InvalidOperationException">If the <see cref="IsLocked"/> property is true.</exception> public static void SetRoot(Func <IConfiguration> getRoot) { if (getRoot.IsNull()) { throw new ArgumentNullException(nameof(getRoot)); } _root.SetValue(getRoot); }
/// <summary> /// Configures a converter for the specified target type. Use this method when you want all /// instances of the target type to use the same converter. If you need instances of the target /// type to each use a different converter depending on which member is being populated, use /// the other <see cref="Add{T}(Type, string, Func{string, T})"/> method. /// </summary> /// <param name="targetType">A type that needs a converter.</param> /// <param name="convertFunc">A function that does the conversion from string to <typeparamref name="T"/>.</param> /// <returns>This instance of <see cref="ValueConverters"/>.</returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="targetType"/> or <paramref name="convertFunc"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the <typeparamref name="T"/> type is not assignable to <paramref name="targetType"/>. /// </exception> public ValueConverters Add <T>(Type targetType, Func <string, T> convertFunc) { if (convertFunc.IsNull()) { throw new ArgumentNullException(nameof(convertFunc)); } return(Add(targetType, typeof(T), value => convertFunc(value))); }
/// <summary> /// Func<T>3个泛型参数,泛型返回值,多播委托扩展 /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="TR"></typeparam> /// <param name="self"></param> /// <param name="func"></param> /// <returns></returns> public static Func <T1, T2, T3, TR> RegFunc <T1, T2, T3, TR>(this Func <T1, T2, T3, TR> self, Func <T1, T2, T3, TR> func) { if (self.IsNull()) { self = func; } self += func; return(self); }
/// <summary> /// Func<T>无泛型参数,泛型返回值,多播委托扩展 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <param name="func"></param> /// <returns></returns> public static Func <T> RegFunc <T>(this Func <T> self, Func <T> func) { if (self.IsNull()) { self = func; } self += func; return(self); }
private static void SetAclCacheProvider( HttpConfiguration config, Func<ICache> cacheProvider) { if (cacheProvider.IsNull()) return; config .GetAclConfiguration() .RegisterAclCacheProvider(cacheProvider); }
public ValueSet(Func <TValue, TKey> keyGenerator) { if (keyGenerator.IsNull()) { throw new ArgumentNullException("keyGenerator"); } _keyGenerator = keyGenerator; _values = new Dictionary <TKey, TValue>(); }
public static T EndInvokeFunc <T>(IAsyncResult result) { Func <T> func = result.AsyncState as Func <T>; if (func.IsNull()) { return(default(T)); } return(func.EndInvoke(result)); }
protected ActionResult ValidateAndSendCommand(Command command, Func<ActionResult> successFunc, Func<ActionResult> failFunc, Func<ActionResult> validationFailFunc = null, Func<bool> preCondition = null, Func<ActionResult> preConditionResult = null) { if (preCondition.IsNull() || preCondition()) { if (ModelState.IsValid) { _commandBus.Send(command); return successFunc(); } else if(validationFailFunc.IsNotNull()) { return validationFailFunc(); } } else if (preConditionResult.IsNotNull()) { return preConditionResult(); } return failFunc(); }