示例#1
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var sessionKey = context.SessionKey;
            var lockKey    = "rule:cart:carttotalrule:" + sessionKey.ToString();

            if (KeyedLock.IsLockHeld(lockKey))
            {
                return(false);
            }

            // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page.
            using (KeyedLock.Lock(lockKey))
            {
                var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

                var cartTotal = ((decimal?)_orderTotalCalculationService.GetShoppingCartTotal(cart)) ?? decimal.Zero;

                // Currency values must be rounded, otherwise unexpected results may occur.
                var money = new Money(cartTotal, context.WorkContext.WorkingCurrency);
                cartTotal = money.RoundedAmount;

                var result = expression.Operator.Match(cartTotal, expression.Value);
                return(result);
            }
        }
        public void Test001()
        {
            var input    = "C1:[] => Issue(claim = C1);";
            var expected = new RuleExpression(
                new[]
            {
                new ConditionExpression(
                    new IdentifierExpression("C1"),
                    Enumerable.Empty <BinaryExpression>()
                    )
            },
                new IssueExpression(
                    new LiteralExpression("Issue"),
                    new[]
            {
                new BinaryExpression(
                    new ClaimPropertyExpression("claim"),
                    new LiteralExpression("="),
                    new IdentifierExpression("C1")
                    )
            }
                    )
                );
            var actual = this.Parser.Parse(input);

            Assert.AreEqual(expected, actual);
        }
示例#3
0
        public async Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var match = false;

            foreach (var expr in _group.Expressions.Cast <RuleExpression>())
            {
                if (expr.Descriptor is not CartRuleDescriptor descriptor)
                {
                    continue;
                }

                var processor = _cartRuleProvider.GetProcessor(expr);

                match = await processor.MatchAsync(context, expr);

                if (!match && _group.LogicalOperator == LogicalRuleOperator.And)
                {
                    break;
                }

                if (match && _group.LogicalOperator == LogicalRuleOperator.Or)
                {
                    break;
                }
            }

            return(match);
        }
示例#4
0
        public Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var roleIds = context.Customer.GetRoleIds();
            var match   = expression.HasListsMatch(roleIds);

            return(Task.FromResult(match));
        }
示例#5
0
 internal ParserNode(Rule rule, RuleExpression expression)
 {
     this.Parent            = null;
     this.IndexInParentList = -1;
     this.Rule       = rule;
     this.Expression = expression;
 }
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var cart         = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);
            var productCount = cart.GetTotalProducts();

            return(expression.Operator.Match(productCount, expression.Value));
        }
示例#7
0
        public Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var country = _countryLookup.LookupCountry(_webHelper.GetClientIpAddress());
            var match   = expression.HasListMatch(country?.IsoCode ?? string.Empty, StringComparer.InvariantCultureIgnoreCase);

            return(Task.FromResult(match));
        }
        public override IRuleExpression VisitRule(RuleEntity rule)
        {
            var expression = new RuleExpression();

            base.ConvertRule(rule, expression);
            return(expression);
        }
示例#9
0
        public Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var paymentMethod = context.Customer.GenericAttributes.Get <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, context.Store.Id);
            var match         = expression.HasListMatch(paymentMethod.NullEmpty(), StringComparer.InvariantCultureIgnoreCase);

            return(Task.FromResult(match));
        }
示例#10
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var query      = _orderService.GetOrders(context.Store.Id, context.Customer.Id, null, null, null, null, null, null, null, null);
            var orderCount = query.Count();

            return(expression.Operator.Match(orderCount, expression.Value));
        }
示例#11
0
        public async Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var sessionKey = context.SessionKey;
            var lockKey    = "rule:cart:cartsubtotalrule:" + sessionKey.ToString();

            if (AsyncLock.IsLockHeld(lockKey))
            {
                //$"locked expression {expression.Id}: {lockKey}".Dump();
                return(false);
            }

            // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page.
            using (await AsyncLock.KeyedAsync(lockKey))
            {
                var cart = await _shoppingCartService.GetCartItemsAsync(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

                var subtotal = await _orderCalculationService.GetShoppingCartSubtotalAsync(cart);

                // Subtotal is always calculated for working currency. No new money struct required here.
                // Currency values must be rounded here because otherwise unexpected results may occur.
                var cartSubtotal = subtotal.SubtotalWithoutDiscount.RoundedAmount;

                var result = expression.Operator.Match(cartSubtotal, expression.Value);
                //$"unlocked expression {expression.Id}: {lockKey}".Dump();
                return(result);
            }
        }
示例#12
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            bool match = false;

            foreach (var expr in _group.Expressions.Cast <RuleExpression>())
            {
                var descriptor = expr.Descriptor as CartRuleDescriptor;
                if (descriptor == null)
                {
                    continue;
                }

                var processor = _cartRuleService.GetProcessor(expr);

                match = processor.Match(context, expr);

                if (!match && _group.LogicalOperator == LogicalRuleOperator.And)
                {
                    break;
                }

                if (match && _group.LogicalOperator == LogicalRuleOperator.Or)
                {
                    break;
                }
            }

            return(match);
        }
示例#13
0
        protected RuleExpression GetOtherExpression(RuleExpression expression)
        {
            var ruleSetId       = expression.Value.Convert <int>();
            var otherExpression = _ruleFactory.CreateExpressionGroup(ruleSetId, _cartRuleProvider) as RuleExpression;

            return(otherExpression);
        }
示例#14
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var lockKey = $"rule:cart:cartsubtotalrule:{Thread.CurrentThread.ManagedThreadId}-{expression.Id}";

            if (KeyedLock.IsLockHeld(lockKey))
            {
                //$"locked: {lockKey}".Dump();
                return(false);
            }

            // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page.
            using (KeyedLock.Lock(lockKey))
            {
                var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

                _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out _, out _, out var cartSubtotal, out _);

                // Currency values must be rounded, otherwise unexpected results may occur.
                var money = new Money(cartSubtotal, context.WorkContext.WorkingCurrency);
                cartSubtotal = money.RoundedAmount;

                var result = expression.Operator.Match(cartSubtotal, expression.Value);
                //$"unlocked {result}: {lockKey}".Dump();
                return(result);
            }
        }
示例#15
0
        protected async Task <RuleExpression> GetOtherExpressionAsync(RuleExpression expression)
        {
            var ruleSetId       = expression.Value.Convert <int>();
            var otherExpression = await _ruleService.CreateExpressionGroupAsync(ruleSetId, _cartRuleProvider) as RuleExpression;

            return(otherExpression);
        }
示例#16
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var otherExpression = GetOtherExpression(expression);

            if (otherExpression == null)
            {
                // Skip\ignore expression.
                return(true);
            }

            var otherRule = _cartRuleProvider.GetProcessor(otherExpression);

            //var otherMatch = otherRule.Match(context, otherExpression);

            //return expression.Operator.Match(otherMatch, true);

            if (expression.Operator == RuleOperator.IsEqualTo)
            {
                return(otherRule.Match(context, otherExpression));
            }
            if (expression.Operator == RuleOperator.IsNotEqualTo)
            {
                return(!otherRule.Match(context, otherExpression));
            }

            throw new InvalidRuleOperatorException(expression);
        }
示例#17
0
        public override async Task <IRuleExpression> VisitRuleAsync(RuleEntity rule)
        {
            var expression = new RuleExpression();
            await base.ConvertRuleAsync(rule, expression);

            return(expression);
        }
示例#18
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            // INFO/TODO: get cart total from somewhere
            var cartTotal = 1000d;

            return(expression.Operator.Match(cartTotal, expression.Value));
        }
示例#19
0
        public async Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var sessionKey = context.SessionKey;
            var lockKey    = "rule:cart:cartsubtotalrule:" + sessionKey.ToString();

            if (AsyncLock.IsLockHeld(lockKey))
            {
                //$"locked expression {expression.Id}: {lockKey}".Dump();
                return(false);
            }

            // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page.
            using (await AsyncLock.KeyedAsync(lockKey))
            {
                var cart = await _shoppingCartService.GetCartItemsAsync(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

                // TODO: (mg) (core) Complete CartSubtotalRule (IOrderTotalCalculationService required).
                //await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, out _, out _, out var cartSubtotal, out _);
                var cartSubtotal = decimal.Zero;

                // Currency values must be rounded, otherwise unexpected results may occur.
                var money = new Money(cartSubtotal, context.WorkContext.WorkingCurrency);
                cartSubtotal = money.RoundedAmount;

                var result = expression.Operator.Match(cartSubtotal, expression.Value);
                //$"unlocked expression {expression.Id}: {lockKey}".Dump();
                return(result);
            }
        }
示例#20
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var result = true;

            // We must prevent the rule from indirectly calling itself. It would cause a stack overflow on cart page
            // and wrong discount calculation (due to MergeWithCombination, if the cart contains a product several times).
            if (Interlocked.CompareExchange(ref _reentrancyNum, 1, 0) == 0)
            {
                try
                {
                    var cart = _shoppingCartService.GetCartItems(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

                    var cartTotal = ((decimal?)_orderTotalCalculationService.GetShoppingCartTotal(cart)) ?? decimal.Zero;

                    // Currency values must be rounded, otherwise unexpected results may occur.
                    var money = new Money(cartTotal, context.WorkContext.WorkingCurrency);
                    cartTotal = money.RoundedAmount;

                    result = expression.Operator.Match(cartTotal, expression.Value);
                }
                finally
                {
                    _reentrancyNum = 0;
                }
            }

            return(result);
        }
示例#21
0
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var list = expression.Value as List <T>;

            if (list == null || list.Count == 0)
            {
                return(true);
            }

            var value = GetValue(context);

            if (object.Equals(value, default(T)))
            {
                return(false);
            }
            if (expression.Operator == RuleOperator.In)
            {
                return(list.Contains(value));
            }
            if (expression.Operator == RuleOperator.NotIn)
            {
                return(!list.Contains(value));
            }

            throw new InvalidRuleOperatorException(expression);
        }
        public bool Match(CartRuleContext context, RuleExpression expression)
        {
            var query        = _customerContentService.GetAllCustomerContent <ProductReview>(context.Customer.Id, true).SourceQuery;
            var reviewsCount = query.Count();

            return(expression.Operator.Match(reviewsCount, expression.Value));
        }
示例#23
0
        public Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var shippingMethod = context.Customer.GenericAttributes.Get <ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, context.Store.Id);
            var match          = expression.HasListMatch(shippingMethod?.ShippingMethodId ?? 0);

            return(Task.FromResult(match));
        }
示例#24
0
        private ParserNode BuildGraphInternal(RuleExpression rootExpression)
        {
            _currContext = GraphContext.ForRoot(rootExpression);

            _recursiveNodes.Clear();
            do
            {
                var ctx = _currContext;

                if (ctx.expression != null)
                {
                    ctx.expression.Visit(_expressionsVisitor);
                }
                else
                {
                    throw new NotImplementedException(); // should never happen
                }

                if (_currContext == ctx)
                {
                    throw new InvalidOperationException(string.Format("Missing transition for expression [{0}] of rule [{1}] was not created!", _currContext.expression, _currContext.rule));
                }
                if (_currContext == null)
                {
                    throw new InvalidOperationException(string.Format("Invalid handler for expression [{0}] of rule [{1}]!", _currContext.expression, _currContext.rule));
                }
                //if (_currContext.prevContext != ctx)
                //    throw new InvalidOperationException(string.Format("Invalid previos context was set from handler for expression [{0}] of rule [{1}] was not created!", _currContext.expression, _currContext.rule));
            } while (_currContext.parentContext != null);

            if (_currContext.childEntries == null ||
                _currContext.childEntries.prev != null)
            {
                throw new InvalidOperationException();
            }

            foreach (var item in _recursiveNodes)
            {
                ParserNode target = null;
                for (var n = item.Parent; n != null; n = n.Parent)
                {
                    if (n.Rule == item.Rule && n.Parent.Rule != item.Rule && n.Parent is ParserNode.RuleCall)
                    // && item.TargetCallExpr.ToString() && )
                    {
                        target = n.Parent;
                        break;
                    }
                }

                if (target == null)
                {
                    throw new InvalidOperationException(string.Format("Filed to find recursive rule call target for rule [{0}] from rule [{1}]!", item.Rule, item.Parent.Rule));
                }

                item.SetTarget(target);
            }

            return(_currContext.childEntries.node);
        }
        public static RuleExpression Caption_EndsWith_Time_Stamp()
        {
            RuleExpression expression = new RuleExpression(
                "Caption", ComparisonConditionEnum.EndsWith, "Time Stamp"
                );

            return(expression);
        }
示例#26
0
 private GraphContext(ExplicitRule rule, RuleExpression expression, GraphContext parentContext, int invocationCount, ChildParserNodeEntry childs)
 {
     this.rule            = rule;
     this.expression      = expression;
     this.parentContext   = parentContext;
     this.invocationCount = invocationCount;
     this.childEntries    = childs;
 }
        public static RuleExpression PhysicalName_EndsWith_Term(string term)
        {
            RuleExpression expression = new RuleExpression(
                "PhysicalName", ComparisonConditionEnum.EndsWith, term
                );

            return(expression);
        }
示例#28
0
        public async Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var count = await _db.Orders
                        .ApplyStandardFilter(context.Customer.Id, context.Store.Id)
                        .CountAsync();

            return(expression.Operator.Match(count, expression.Value));
        }
        public async Task <bool> MatchAsync(CartRuleContext context, RuleExpression expression)
        {
            var cart = await _shoppingCartService.GetCartItemsAsync(context.Customer, ShoppingCartType.ShoppingCart, context.Store.Id);

            var productCount = cart.GetTotalQuantity();

            return(expression.Operator.Match(productCount, expression.Value));
        }
        public void TestParameter(string expression, int p1, double p2, double result)
        {
            var jRuleExpression = new RuleExpression <Func <int, decimal, decimal> >();
            var function        = jRuleExpression.Function(expression);

            var result1 = function(p1, (decimal)p2);

            Assert.AreEqual((decimal)result, result1);
        }
 public void TypeOfSimpleTarget()
 {
     var re = new RuleExpression("SomeString");
     Assert.AreEqual(typeof(string), re.GetExpressionType(_context));
 }
示例#32
0
        /// <summary>
        /// Add an operating system requirement to an existing deployment type
        /// </summary>
        public static void AddRequirement(string applicationName, OperatingSystemValues os, string server)
        {
            Application app = CMApplication.GetApplicationByName(applicationName, server);
            DeploymentType deploymentType = app.DeploymentTypes[0];

            string ruleExpressionText = string.Empty;
            string ruleAnnotationText = string.Empty;

            switch (os)
            {
                case OperatingSystemValues.Windows81x86:
                    ruleExpressionText = "Windows/All_x86_Windows_8.1_Client";
                    ruleAnnotationText = "Operating system One of {All Windows 8.1(32 - bit)}";
                    break;
                case OperatingSystemValues.Windows81x64:
                    ruleExpressionText = "Windows/All_x64_Windows_8.1_Client";
                    ruleAnnotationText = "Operating system One of {All Windows 8.1(64 - bit)}";
                    break;
                case OperatingSystemValues.Windows10x86:
                    ruleExpressionText = "Windows/All_x86_Windows_10_and_higher_Clients";
                    ruleAnnotationText = "Operating system One of {All Windows 10 Professional/Enterprise and higher (32 - bit)}";
                    break;
                case OperatingSystemValues.Windows10x64:
                    ruleExpressionText = "Windows/All_x64_Windows_10_and_higher_Clients";
                    ruleAnnotationText = "Operating system One of {All Windows 10 Professional/Enterprise and higher (64 - bit)}";
                    break;
            }

            CustomCollection<RuleExpression> ruleCollection = new CustomCollection<RuleExpression>();
            RuleExpression ruleExpression = new RuleExpression(ruleExpressionText);
            ruleCollection.Add(ruleExpression);

            OperatingSystemExpression osExpression = new OperatingSystemExpression(ExpressionOperator.OneOf, ruleCollection);

            Rule rule = new Rule(Guid.NewGuid().ToString("N"), NoncomplianceSeverity.None, new Annotation(ruleAnnotationText, null, null, null), osExpression);

            deploymentType.Requirements.Add(rule);
            CMApplication.Save(app, server);
        }
 public void UnassignedSimpleTargetIsInvalid()
 {
     var re = new RuleExpression("Whatever");
     Assert.IsFalse(re.IsValid(_context));
 }
 public void AssignedTargetMethodIsValid()
 {
     var re = new RuleExpression("Person.IsMinor");
     Assert.IsTrue(re.IsValid(_context));
 }
 public void InvalidMemberIsInvalid()
 {
     var re = new RuleExpression("Person.Whatever");
     Assert.IsFalse(re.IsValid(_context));
 }
 public void TypeOfMethod()
 {
     var re = new RuleExpression("Person.Age");
     Assert.AreEqual(typeof(int), re.GetExpressionType(_context));
 }
 public void AssignedTargetPropertyIsValid()
 {
     var re = new RuleExpression("Person.LastName");
     Assert.IsTrue(re.IsValid(_context));
 }
 public void SimpleTargetIsAssignable()
 {
     var re = new RuleExpression("SomeString");
     Assert.IsTrue(re.IsAssignable(_context));
 }
 public void ReadOnlyPropertyIsNotAssignable()
 {
     var re = new RuleExpression("Person.MedicalRecordNumber");
     Assert.IsTrue(re.IsValid(_context));
     Assert.IsFalse(re.IsAssignable(_context));
 }
 public void MethodIsNotAssignable()
 {
     var re = new RuleExpression("Person.Age");
     Assert.IsTrue(re.IsValid(_context));
     Assert.IsFalse(re.IsAssignable(_context));
 }
 public void TypeOfProperty()
 {
     var re = new RuleExpression("Person.IsPhysician");
     Assert.AreEqual(typeof(bool), re.GetExpressionType(_context));
 }
 public void UnassignedTargetIsInvalid()
 {
     var re = new RuleExpression("Patient.LastName");
     Assert.IsFalse(re.IsValid(_context));
 }
示例#43
0
        //public override bool Check(ref ICheckResult ppResult)
        //{
        //    return true;
        //    // ������ͼ��ı���ת��Ϊ��ʵ����
        //    InitTopoLayerArray();
        //    CTopoConstruct topoObj = new CTopoConstruct();
        //    // ��ʼ��
        //    string strTopoName = "" + m_strID + "_Topology";
        //    if (!topoObj.Init(ref m_psRuleParas, strTopoName, m_pSonEngineWks))
        //    {
        //        return false;
        //    }
        //    // ��������
        //    bool state = topoObj.ConstructTopo();
        //    if (state != true)
        //    {
        //        return state;
        //    }
        //    ppResult = null;
        //    return true;
        //}
        // �������˽ṹ����IJ���
        private bool ParseTopoPara(string strTopoPara, RuleExpression.LRTopoParas psRulePara)
        {
            if (strTopoPara == "")
            {
                return false;
            }
            string para_str = strTopoPara;
            m_psRuleParas.arraySeledLayers = new List<string>();
            m_psRuleParas.arrayOrigLayers = new List<string>();

            string para_tmp1, para_tmp2, para_tmp3;

            string[] strList = para_str.Split('#');
            para_tmp1 = strList[0];
            para_tmp2 = strList[1];
            para_tmp3 = strList[2];

            int j = 0;
            string[] strResult = para_tmp1.Split('|');
            m_psRuleParas.strTopoName = strResult[j++]; //��������
            m_psRuleParas.strStandardName = strResult[j++]; //��׼����
            m_psRuleParas.strSourceLayer = strResult[j]; //�����ͼ��,��Ŀ��ͼ��

            string[] strResult1 = para_tmp2.Split('|');
            for (j = 0; j < strResult1.Length; j++)
            {
                m_psRuleParas.arrayOrigLayers.Add(strResult1[j]);
            }

            string[] strResult2 = para_tmp3.Split('|');
            for (j = 0; j < strResult2.Length; j++)
            {
                if (strResult2[j] != "")
                {
                    m_psRuleParas.arraySeledLayers.Add(strResult2[j]);
                }
            }

            return true;
        }
 public void EmptyExpressionIsInvalid()
 {
     var re = new RuleExpression { };
     Assert.IsFalse(re.IsValid(_context));
 }
 public void WritablePropertyIsAssignable()
 {
     var re = new RuleExpression("Person.Salutation");
     Assert.IsTrue(re.IsAssignable(_context));
 }
 public void AssignedSimpleTargetIsValid()
 {
     var re = new RuleExpression("SomeString");
     Assert.IsTrue(re.IsValid(_context));
 }