public virtual Task <T> FindOneAsync <T, TKey>(TKey key, CancellationToken cancellationToken = default) where T : class, IObject <TKey> { var queryable = this.GetQuery <T>().Where(ExpressionExtensions.Equals <T, TKey>(ExpressionExtensions.GetPropertyName <T, TKey>(e => e.Id), key)); return(queryable.FirstOrDefaultAsync(cancellationToken)); }
/// <summary> /// Register the methods /// </summary> /// <param name="interceptor"></param> public override void Initialize(IExtensibleInterceptor interceptor) { base.Initialize(interceptor); // this registers one method and the overloading is handled in the GetDefaultValue interceptor.RegisterMethod(ExpressionExtensions.GetMemberName <IDefaultValue>(x => x.DefaultValueFor("")), GetDefaultValue); interceptor.RegisterMethod(ExpressionExtensions.GetMemberName <IDefaultValue>(x => x.RestoreToDefault("")), RestoreToDefault); }
private Expression GetAssignExpression(Type propertyType, FilterOperator filterOperator, Expression left, ConstantExpression right) { var effectiveType = propertyType.GetEffectiveType(); if ((effectiveType == typeof(string)) || (effectiveType == typeof(Guid))) { return(ExpressionExtensions.GetAssignExpressionString(filterOperator, left, right, propertyType)); } if (effectiveType.IsNumericType()) { return(ExpressionExtensions.GetAssignExpressionNumeric(filterOperator, left, right, propertyType)); } if (effectiveType == typeof(bool)) { return(ExpressionExtensions.GetAssignExpressionBoolean(filterOperator, left, right, propertyType)); } if (effectiveType == typeof(DateTime)) { return(ExpressionExtensions.GetAssignExpressionDateTime(filterOperator, left, right, propertyType)); } if (effectiveType.IsEnum()) { return(ExpressionExtensions.GetAssignExpressionEnum(filterOperator, left, right, propertyType)); } return(null); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual SqlExpression Translate( SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments, IDiagnosticsLogger <DbLoggerCategory.Query> logger) { Check.NotNull(method, nameof(method)); Check.NotNull(arguments, nameof(arguments)); Check.NotNull(logger, nameof(logger)); if (method.Equals(_regexIsMatchMethodInfo)) { var input = arguments[0]; var pattern = arguments[1]; var stringTypeMapping = ExpressionExtensions.InferTypeMapping(input, pattern); return(_sqlExpressionFactory.Function( "regexp", new[] { _sqlExpressionFactory.ApplyTypeMapping(pattern, stringTypeMapping), _sqlExpressionFactory.ApplyTypeMapping(input, stringTypeMapping) }, nullable: true, argumentsPropagateNullability: new[] { true, true }, typeof(bool))); } return(null); }
public void ValidatePropertyExpressionType_WithIncompatiblePropertyType_ShouldFail() { var collectionPropExpression = GetExpression <ModelWithObservableCollection, string>(m => m.CollectionProp); Assert.Throws <ArgumentException>(() => ExpressionExtensions.ValidatePropertyExpressionType <ModelWithObservableCollection, string, Collection <string> >(collectionPropExpression)); }
public override object Evaluate() { IList <double> v = LeftExpression.EvaluateAsRealVector(); if (RightExpression == Expression <Object> .Null) { return(new CMatrix(MathStats.Histogram(v))); } else { object intvals = RightExpression.Evaluate(); if (intvals is Complex) { return(new CMatrix(MathStats.Histogram(v, ExpressionExtensions.AsInt32((Complex)intvals)))); } else if (intvals is CMatrix) { return(new CMatrix(MathStats.Histogram(v, ExpressionExtensions.AsRealVector((CMatrix)intvals)))); } else { throw ExceptionHelper.ThrowWrongArgumentType(intvals); } } }
/// <summary> /// Register methods /// </summary> /// <param name="interceptor"></param> public override void Initialize(IExtensibleInterceptor interceptor) { base.Initialize(interceptor); // this registers one method and the overloading is handled in the GetDescription interceptor.RegisterMethod(ExpressionExtensions.GetMemberName <IDescription>(x => x.DescriptionFor("")), GetDescription); }
public void Write(Hadith hadith) { if (hadith.Id <= 0) { throw new ArgumentOutOfRangeException(nameof(Hadith.Id)); } var document = new Document(); document.Boost = DocumentWeights.Weights["Hadith-" + hadith.CollectionCode]; document.StoreAndIndex(hadith, x => x.Id); foreach (VerseRangeReference verseRangeReference in hadith.VerseRangeReferences) { string indexName = ExpressionExtensions.GetIndexName <Hadith, object>(x => x.VerseRangeReferences); document.StoreAndIndex(indexName, verseRangeReference.ToIndexValue()); } document.AddSearchableText(hadith.ArabicText); document.AddSearchableText(hadith.EnglishText); document.StoreAndIndex(hadith, x => x.CollectionCode); document.StoreAndIndex(hadith, x => x.PrimaryReferenceCode); document.StoreAndIndex(hadith, x => x.PrimaryReferencePath); document.AddObject(hadith); IndexWriter indexWriter = IndexWriterProvider.GetIndexWriter(); indexWriter.AddDocument(document); WriteHadithReferences(indexWriter, hadith); WriteVerseReferences(indexWriter, hadith); }
public void ShouldReturnEnumerableOnExpression() { var source = Expression.Empty(); var actual = ExpressionExtensions.AsEnumerable(source); Assert.IsAssignableFrom <IEnumerable <Expression> >(actual); }
public IQueryable <TEntity> Query(FeedOptions feedOptions = null) { var queryable = CosmonautClient.Query <TEntity>(DatabaseName, CollectionName, GetFeedOptionsForQuery(feedOptions)); return(IsShared ? queryable.Where(ExpressionExtensions.SharedCollectionExpression <TEntity>()) : queryable); }
public void ToCSharpString_ArgumentChecking() { Assert.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.ToCSharpString(expression: null)); Assert.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.ToCSharp(expression: null)); Assert.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.ToCSharpString(expression: null, allowCompilerGeneratedNames: false)); Assert.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.ToCSharp(expression: null, allowCompilerGeneratedNames: false)); }
//--------------------------------------------------------------------- public override DesignerActionItemCollection GetSortedActionItems() { var actionPropertiesHeader = new DesignerActionHeaderItem("Свойства", "Properties"); var items = new DesignerActionItemCollection { actionPropertiesHeader }; //----------------------------------------------------------------- items.AddActionPropertyItem( nameof(RadiusCorner), _control.GetPropertyName(ExpressionExtensions.LastPartNameOf(() => _control.RadiusCorner)), actionPropertiesHeader.Category ); //----------------------------------------------------------------- var actionMethodsHeader = new DesignerActionHeaderItem("Методы", "Methods"); items.Add(actionMethodsHeader); //------------------------------------------------------------- items.Add(new DesignerActionMethodItem( this, nameof(AddNewTab), "Добавить новую страницу", actionMethodsHeader.Category )); return(items); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual SqlExpression Translate( SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments, IDiagnosticsLogger <DbLoggerCategory.Query> logger) { Check.NotNull(method, nameof(method)); Check.NotNull(arguments, nameof(arguments)); Check.NotNull(logger, nameof(logger)); if (_methodInfoDateDiffMapping.TryGetValue(method, out var datePart)) { var startDate = arguments[1]; var endDate = arguments[2]; var typeMapping = ExpressionExtensions.InferTypeMapping(startDate, endDate); startDate = _sqlExpressionFactory.ApplyTypeMapping(startDate, typeMapping); endDate = _sqlExpressionFactory.ApplyTypeMapping(endDate, typeMapping); return(_sqlExpressionFactory.Function( "DATEDIFF", new[] { _sqlExpressionFactory.Fragment(datePart), startDate, endDate }, nullable: true, argumentsPropagateNullability: new[] { false, true, true }, typeof(int))); } return(null); }
public void IsValidLambdaExpression_False_WhenNull() { var actual = ExpressionExtensions.IsValidLambdaExpression(null, out LambdaExpression lambda); Assert.False(actual); Assert.Null(lambda); }
private Expression NullCheck(Expression input) { var underlyingType = input.Type.GetTypeOfNullable(); var nullSubstitute = ExpressionExtensions.ToType(Constant(_nullSubstitute), underlyingType); return(Condition(Property(input, "HasValue"), Property(input, "Value"), nullSubstitute, underlyingType)); }
public override SqlFunctionExpression Coalesce( SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null ) { left.ThrowIfNull(nameof(left)); right.ThrowIfNull(nameof(right)); var resultType = right.Type; var inferredTypeMapping = typeMapping ?? ExpressionExtensions.InferTypeMapping(left, right) ?? _typeMappingSource.FindMapping(resultType); var typeMappedArguments = new List <SqlExpression>() { ApplyTypeMapping(left, inferredTypeMapping), ApplyTypeMapping(right, inferredTypeMapping) }; return(new SqlFunctionExpression( null, "NVL", typeMappedArguments, true, new[] { false, false }, resultType, inferredTypeMapping )); }
private SqlExpression ApplyTypeMappingOnMySqlBinary( MySqlBinaryExpression sqlBinaryExpression, RelationalTypeMapping typeMapping) { var left = sqlBinaryExpression.Left; var right = sqlBinaryExpression.Right; Type resultType; RelationalTypeMapping resultTypeMapping; RelationalTypeMapping inferredTypeMapping; switch (sqlBinaryExpression.OperatorType) { case MySqlBinaryExpressionOperatorType.IntegerDivision: { inferredTypeMapping = typeMapping ?? ExpressionExtensions.InferTypeMapping(left, right); resultType = left.Type; resultTypeMapping = inferredTypeMapping; } break; default: throw new InvalidOperationException("Incorrect OperatorType for MySqlBinaryExpression"); } return(new MySqlBinaryExpression( sqlBinaryExpression.OperatorType, ApplyTypeMapping(left, inferredTypeMapping), ApplyTypeMapping(right, inferredTypeMapping), resultType, resultTypeMapping)); }
public async Task <List <SlopeEntity> > GetPageList(int pageIndex, int pageSize, string disasterunitname, string location) { var query = new List <SlopeEntity>(); var eps = ExpressionExtensions.True <SlopeEntity>(); if (disasterunitname == "" && location == "") { query = GetAll().OrderBy(s => s.UNIFIEDCODE).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } else { if (disasterunitname != "") { eps = eps.And(s => s.DISASTERUNITNAME == disasterunitname); } if (location != "") { eps = eps.And(s => s.LOCATION == location); } query = GetAll().Where(eps).OrderBy(s => s.UNIFIEDCODE).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } return(query); }
public virtual SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments) { if (_supportedMethods.TryGetValue(method, out var sqlFunctionName)) { RelationalTypeMapping typeMapping; List <SqlExpression> newArguments = null; if (string.Equals(sqlFunctionName, "max") || string.Equals(sqlFunctionName, "max")) { typeMapping = ExpressionExtensions.InferTypeMapping(arguments[0], arguments[1]); newArguments = new List <SqlExpression> { _sqlExpressionFactory.ApplyTypeMapping(arguments[0], typeMapping), _sqlExpressionFactory.ApplyTypeMapping(arguments[1], typeMapping) }; } else { typeMapping = arguments[0].TypeMapping; } return(_sqlExpressionFactory.Function( sqlFunctionName, newArguments ?? arguments, method.ReturnType, typeMapping)); } return(null); }
private SqlExpression TranslateStartsEndsWith(SqlExpression instance, SqlExpression pattern, bool startsWith) { var stringTypeMapping = ExpressionExtensions.InferTypeMapping(instance, pattern); instance = _sqlExpressionFactory.ApplyTypeMapping(instance, stringTypeMapping); pattern = _sqlExpressionFactory.ApplyTypeMapping(pattern, stringTypeMapping); if (pattern is SqlConstantExpression constantExpression) { // The pattern is constant. Aside from null or empty, we escape all special characters (%, _, \) // in C# and send a simple LIKE if (!(constantExpression.Value is string constantString)) { return(_sqlExpressionFactory.Like( instance, _sqlExpressionFactory.Constant(null, stringTypeMapping))); } return(constantString.Any(c => IsLikeWildChar(c)) ? _sqlExpressionFactory.Like( instance, _sqlExpressionFactory.Constant( startsWith ? EscapeLikePattern(constantString) + '%' : '%' + EscapeLikePattern(constantString)), _sqlExpressionFactory.Constant( LikeEscapeChar.ToString())) // SQL Server has no char mapping, avoid value conversion warning) : _sqlExpressionFactory.Like( instance, _sqlExpressionFactory.Constant(startsWith ? constantString + '%' : '%' + constantString))); } // The pattern is non-constant, we use LEFT or RIGHT to extract substring and compare. // For StartsWith we also first run a LIKE to quickly filter out most non-matching results (sargable, but imprecise // because of wildchars). if (startsWith) { return(_sqlExpressionFactory.AndAlso( _sqlExpressionFactory.Like( instance, _sqlExpressionFactory.Add( instance, _sqlExpressionFactory.Constant("%"))), _sqlExpressionFactory.Equal( _sqlExpressionFactory.Function( "LEFT", new[] { instance, _sqlExpressionFactory.Function("LEN", new[] { pattern }, typeof(int)) }, typeof(string), stringTypeMapping), pattern))); } return(_sqlExpressionFactory.Equal( _sqlExpressionFactory.Function( "RIGHT", new[] { instance, _sqlExpressionFactory.Function("LEN", new[] { pattern }, typeof(int)) }, typeof(string), stringTypeMapping), pattern)); }
private static void AssertDictionaryEquivalence( IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); string methodName = ExpressionExtensions.GetMethodName( () => AssertDictionaryEquivalence <object, object, object, object>(null, null, null, null, null)); var assertDictionaryEquivalence = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(context.Expectation.GetType())) .ToArray(), Expression.Constant(context), Expression.Constant(parent), Expression.Constant(config), Expression.Constant(context.Subject, GetIDictionaryInterface(subjectType)), Expression.Constant(context.Expectation, GetIDictionaryInterface(context.Expectation.GetType()))); Expression.Lambda(assertDictionaryEquivalence).Compile().DynamicInvoke(); }
/// <summary> /// Transmit all queued messages to the given <paramref name="peer"/>. /// </summary> /// <param name="peer">The peer to synchronise.</param> /// <returns>An awaitable object representing the synchronise operation.</returns> public async Task SynchroniseAsync(IPeer peer) { Argument.CannotBeNull(peer, "peer", "The peer to synchronise cannot be null."); try { var message = this._queueManager.PeersNextMessageOrDefault(peer); var sendMessageTasks = new List <Task>(); while (message != null) { var messagePointer = message; sendMessageTasks.Add(Task.Factory.StartNew(() => this._transport.SendMessageAsync(messagePointer))); message = this._queueManager.PeersNextMessageOrDefault(peer, message.QueuedAt); } await Task.WhenAll(sendMessageTasks); } catch (Exception ex) { this.RaiseUnahndledExceptionEvent(ex, ExpressionExtensions.MethodName(() => this.SynchroniseAsync(null))); throw; } }
public void ThrowsWhenPassedNonProperty() { Assert.Throws(typeof(ArgumentException), () => { ExpressionExtensions.ToPropertyInfo <Func <string, object> >(s => s.Clone()); }); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual SqlExpression Translate( SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments, IDiagnosticsLogger <DbLoggerCategory.Query> logger) { Check.NotNull(method, nameof(method)); Check.NotNull(arguments, nameof(arguments)); Check.NotNull(logger, nameof(logger)); if (_supportedMethodTranslations.TryGetValue(method, out var sqlFunctionName)) { var typeMapping = arguments.Count == 1 ? ExpressionExtensions.InferTypeMapping(arguments[0]) : ExpressionExtensions.InferTypeMapping(arguments[0], arguments[1]); var newArguments = new SqlExpression[arguments.Count]; newArguments[0] = _sqlExpressionFactory.ApplyTypeMapping(arguments[0], typeMapping); if (arguments.Count == 2) { newArguments[1] = _sqlExpressionFactory.ApplyTypeMapping(arguments[1], typeMapping); } return(_sqlExpressionFactory.Function( sqlFunctionName, newArguments, nullable: true, argumentsPropagateNullability: newArguments.Select(a => true).ToArray(), method.ReturnType, sqlFunctionName == "SIGN" ? null : typeMapping)); } if (_truncateMethodInfos.Contains(method)) { var argument = arguments[0]; return(_sqlExpressionFactory.Function( "ROUND", new[] { argument, _sqlExpressionFactory.Constant(0), _sqlExpressionFactory.Constant(1) }, nullable: true, argumentsPropagateNullability: new[] { true, false, false }, method.ReturnType, argument.TypeMapping)); } if (_roundMethodInfos.Contains(method)) { var argument = arguments[0]; var digits = arguments.Count == 2 ? arguments[1] : _sqlExpressionFactory.Constant(0); return(_sqlExpressionFactory.Function( "ROUND", new[] { argument, digits }, nullable: true, argumentsPropagateNullability: new[] { true, true }, method.ReturnType, argument.TypeMapping)); } return(null); }
internal static Expression NewExpr(this Type baseType, Type ifInterfaceType) { var newExpr = baseType.IsInterface() ? Expression.New(ifInterfaceType.MakeGenericType(TypeHelper.GetElementTypes(baseType, ElemntTypeFlags.BreakKeyValuePair))) : DelegateFactory.GenerateConstructorExpression(baseType); return(ExpressionExtensions.ToType(newExpr, baseType)); }
public void TestNoDefaultConstructorSet() { Expression <Func <A, int> > lambda = x => x.BProp.CProp.DProp.Value; A a = new A(); ExpressionExtensions.SetValue(lambda, a, 42); }
public void TestReplaceParameter() { Expression <Func <B, string> > exp = b => b.C.Each().D.E[2].F; Expression <Func <B, string> > expWithReplacedParameter = ExpressionExtensions.Merge <B, B, string>(b => b, exp); expWithReplacedParameter.AssertEqualsExpression(exp); Assert.That(expWithReplacedParameter.Parameters[0], Is.Not.EqualTo(exp.Parameters[0])); }
public void FailSettingMethod() { Expression <Func <A, int> > lambda = x => x.BProp.CProp.DProp.GetValue(); A a = new A(); ExpressionExtensions.SetValue(lambda, a, 50); }
/// <summary> /// Register methods /// </summary> /// <param name="interceptor"></param> public override void Initialize(IExtensibleInterceptor interceptor) { base.Initialize(interceptor); // Use Lambda to make refactoring possible, this registers one method and the overloading is handled in the IsTaggedWith interceptor.RegisterMethod(ExpressionExtensions.GetMemberName <ITagging>(x => x.IsTaggedWith("", null)), IsTaggedWith); interceptor.RegisterMethod(ExpressionExtensions.GetMemberName <ITagging>(x => x.GetTagValue("", null)), GetTagValue); }
public void ExpressionExtensions_Funcletize_ArgumentChecking() { #pragma warning disable IDE0034 // Simplify 'default' expression (illustrative of method signature) AssertEx.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.Funcletize(default(Expression)), ex => Assert.AreEqual("expression", ex.ParamName)); AssertEx.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.Funcletize <int>(default(Expression)), ex => Assert.AreEqual("expression", ex.ParamName)); AssertEx.ThrowsException <ArgumentNullException>(() => ExpressionExtensions.Funcletize <int>(default(Expression <Func <int> >)), ex => Assert.AreEqual("expression", ex.ParamName)); #pragma warning restore IDE0034 // Simplify 'default' expression }