Ejemplo n.º 1
0
		public override PromotionReward[] EvaluatePromotion(IEvaluationContext context)
		{
			var retVal = new List<PromotionReward>();
			var promoContext = context as PromotionEvaluationContext;
			if (promoContext == null)
			{
				throw new ArgumentException("context should be PromotionEvaluationContext");
			}

			//Check coupon
			var couponValid = (Coupons != null && Coupons.Any()) ? Coupons.Any(x=> String.Equals(x, promoContext.Coupon, StringComparison.InvariantCultureIgnoreCase)) : true;

		
			//Evaluate reward for all promoEntry in context
			foreach (var promoEntry in promoContext.PromoEntries)
			{
				//Set current context promo entry for evaluation
				promoContext.PromoEntry = promoEntry;
				foreach (var reward in Rewards.Select(x=>x.Clone()))
				{
					reward.Promotion = this;
					reward.IsValid = couponValid && Condition(promoContext);
					var catalogItemReward = reward as CatalogItemAmountReward;
					//Set productId for catalog item reward
					if (catalogItemReward != null && catalogItemReward.ProductId == null)
					{
						catalogItemReward.ProductId = promoEntry.ProductId;
					}
					retVal.Add(reward);
				}
			}
			return retVal.ToArray();
		}
		public DynamicContentItem[] EvaluateItems(IEvaluationContext context)
		{
			var dynamicContext = context as DynamicContentEvaluationContext;
			if(context == null)
			{
				throw new ArgumentNullException("dynamicContext");
			}
			var retVal = new List<DynamicContentItem>();
			using(var repository = _repositoryFactory())
			{
				var query = repository.PublishingGroups.Include(x => x.ContentItems)
													   .Where(x => x.IsActive)
													   .Where(x => (x.StartDate == null || dynamicContext.ToDate >= x.StartDate) && (x.EndDate == null || x.EndDate >= dynamicContext.ToDate))
													   .Where(x => x.ContentPlaces.Any(y => y.ContentPlace.Name == dynamicContext.PlaceName))
													   .OrderBy(x => x.Priority)
													   .SelectMany(x => x.ContentItems)
													   .Select(x => x.DynamicContentItemId);
				var contentItemIds = query.ToArray();
				foreach (var contentItemId in contentItemIds)
				{
					var contentItem = _dynamicContentService.GetContentItemById(contentItemId);
					retVal.Add(contentItem);
				}
			
			}

			return retVal.ToArray();
		}
Ejemplo n.º 3
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     Type t = OperationHelper.ResolveType(context, _typeName);
     if (t == null)
         throw new TypeLoadException("Failed to resolve type '" + _typeName + "'");
     stack.Push(t);
 }
Ejemplo n.º 4
0
		/////////////////////////////////////////////////////////////////////////////
		/// <summary>
		/// Evaluate the text in the IEvaluationContext, newOutput is currently
		/// ignored - each evaluation gets a new Output object
		/// </summary>
		/// <param name="evx"></param>
		/// <param name="newOutput"></param>
		/// <returns></returns>

		public string Evaluate( IEvaluationContext evx, bool newOutput )
		{
			// ******
			//
			// EvalLock() will throw an exception if this instance of NMP is already
			// evaluating something, it also calls Restore()/Save() for our thread
			// data
			//
			using( new EvalLock( this ) ) {
				try {
					using( var input = gc.GetMasterParseReader( new ParseStringReader( evx.Text, evx.FileName ) ) ) {
						MasterOutput output = GetMasterOutput( newOutput );
						string result = string.Empty;

						// ******
						var mir = new MIR( null, input, "Root" );

						using ( Get<InvocationContext>().Init( mir ) ) {
							SetMacroProcessorOutputInstance( output );
							
							Scanner( input, output );
							StringBuilder sb = output.AllText;
							result = sb.ToString();

							SetMacroProcessorOutputInstance( null );
						}

						// ******
						return result;
					}
				}
				finally {
				}
			}
		}
Ejemplo n.º 5
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     var cond = Utils.To<bool>(stack.Pop());
     if (cond)
         _ifTrue.Eval(context,stack);
     else
         _ifFalse.Eval(context, stack);
 }
        /// <summary>
        /// Expression visitor
        /// </summary>
        /// <param name="context">Evaluation context</param>
        public ExpressionVisitor(IEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.context = context;
        }
Ejemplo n.º 7
0
            public bool CanRead(IEvaluationContext context, object target, string name)
            {
                if (!(target is string))
                {
                    throw new SystemException("Assertion Failed! target should be string");
                }

                return(name.Equals("flibbles"));
            }
Ejemplo n.º 8
0
        public void Initialize(IEvaluationContext context, IDictionary <ParameterAttribute, object> parameterValues)
        {
            foreach (var component in _components)
            {
                component.Initialize(context, parameterValues);
            }

            _context = context;
        }
Ejemplo n.º 9
0
 public override object Evaluate(IEvaluationContext context = null)
 {
     if (context == null)
     {
         context = DefaultContext;
     }
     return(context.GetVariable(_Description));
     //TODO: Fallback behaviour with no context?
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">The evaluation context</param>
        public MultipleExpressionEvaluator(IEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "evaluation context must be provided");
            }

            this.context = context;
        }
Ejemplo n.º 11
0
        public static string ReplaceAt(this IEvaluationContext context, string input, double replace)
        {
            var sb = new StringBuilder();

            sb.Append(input.Substring(0, context.Index));
            sb.Append(replace);
            sb.Append(input.Substring(context.Index + context.Token.Length));
            return(sb.ToString());
        }
Ejemplo n.º 12
0
        public void Write(IEvaluationContext context, object target, string name, object newValue)
        {
            if (target is not IDictionary asDict)
            {
                throw new ArgumentException("Target must be of type IDictionary");
            }

            asDict[name] = newValue;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">The evaluation context</param>
        public MultipleExpressionEvaluator(IEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "evaluation context must be provided");
            }

            this.context = context;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// ((PromotionEvaluationContext)x).CheckItemTags() > NumItem
        /// </summary>
        /// <returns></returns>
        public override bool Evaluate(IEvaluationContext context)
        {
            if (context is PromotionEvaluationContext promotionEvaluationContext)
            {
                return(Tags.Any(x => promotionEvaluationContext.PromoEntry.Attributes.ContainsKey("tag") && string.Equals(promotionEvaluationContext.PromoEntry.Attributes["tag"], x, StringComparison.InvariantCultureIgnoreCase)));
            }

            return(false);
        }
        /// <summary>
        /// Expression visitor
        /// </summary>
        /// <param name="context">Evaluation context</param>
        public ExpressionVisitor(IEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.context = context;
        }
Ejemplo n.º 16
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.boris.expr.Expr evaluate(org.boris.expr.IEvaluationContext paramIEvaluationContext, org.boris.expr.Expr[] paramArrayOfExpr) throws org.boris.expr.ExprException
        public virtual Expr evaluate(IEvaluationContext paramIEvaluationContext, Expr[] paramArrayOfExpr)
        {
            assertArgCount(paramArrayOfExpr, 3);
            ExprArray exprArray = asArray(paramIEvaluationContext, paramArrayOfExpr[0], true);
            double?   double1;
            double?   double2 = (double1 = Convert.ToDouble(asDouble(paramIEvaluationContext, paramArrayOfExpr[1], true) - 1.0D)).valueOf(asDouble(paramIEvaluationContext, paramArrayOfExpr[2], true) - 1.0D);

            return((double2.Value < 0.0D || double2.Value >= exprArray.rows()) ? new ExprDouble(1.0D) : ((double1.Value < 0.0D || double1.Value >= exprArray.columns()) ? new ExprDouble(1.0D) : exprArray.get(double2.Value, double1.Value)));
        }
Ejemplo n.º 17
0
            public ITypedValue Read(IEvaluationContext context, object target, string name)
            {
                if (!name.Equals("flibbles"))
                {
                    throw new SystemException("Assertion Failed! name should be flibbles");
                }

                return(new TypedValue(flibbles));
            }
Ejemplo n.º 18
0
        public ITypedValue Read(IEvaluationContext context, object target, string name)
        {
            if (target is not IConfiguration asConfig)
            {
                throw new ArgumentException("Target must be of type IConfiguration");
            }

            return(new TypedValue(asConfig[name]));
        }
Ejemplo n.º 19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.boris.expr.Expr evaluate(org.boris.expr.IEvaluationContext paramIEvaluationContext, org.boris.expr.Expr[] paramArrayOfExpr) throws org.boris.expr.ExprException
        public virtual Expr evaluate(IEvaluationContext paramIEvaluationContext, Expr[] paramArrayOfExpr)
        {
            assertArgCount(paramArrayOfExpr, 2);
            double           d = asDouble(paramIEvaluationContext, paramArrayOfExpr[0], true);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(asString(paramIEvaluationContext, paramArrayOfExpr[1], true));
            string           str = simpleDateFormat.format(Convert.ToInt64(ExcelDate.toJavaDate(d)));

            return(new ExprString(str));
        }
Ejemplo n.º 20
0
        public override IMethodExecutor Resolve(IEvaluationContext context, object targetObject, string name, List <Type> argumentTypes)
        {
            if (targetObject is Type)
            {
                throw new ArgumentException("DataBindingMethodResolver does not support Class targets");
            }

            return(base.Resolve(context, targetObject, name, argumentTypes));
        }
            public IMethodExecutor Resolve(IEvaluationContext context, object targetObject, string name, List <Type> arguments)
            {
                if (name.Equals("HasRole"))
                {
                    return(new HasRoleExecutor(context.TypeConverter));
                }

                return(null);
            }
        public override bool Evaluate(IEvaluationContext context)
        {
            var result = false;

            if (context is EvaluationContextBase promotionEvaluationContext)
            {
                result = Children.All(c => c.Evaluate(promotionEvaluationContext));
            }
            return(result);
        }
Ejemplo n.º 23
0
        public override float Evaluate(IEvaluationContext context)
        {
            var variable = context.GetVariable(Symbol);

            if (!variable.IsAssigned)
            {
                throw new InvalidOperationException($"Expected variable '{Symbol}' to be set.");
            }
            return(variable.Value.Value);
        }
Ejemplo n.º 24
0
 public PartitioningInterceptor(IExpressionParser expressionParser, IEvaluationContext evaluationContext, IBindingOptions bindingOptions, IPartitionKeyExtractorStrategy partitionKeyExtractorStrategy, IPartitionSelectorStrategy partitionSelectorStrategy)
 {
     _bindingOptions   = bindingOptions;
     _partitionHandler = new PartitionHandler(
         expressionParser,
         evaluationContext,
         _bindingOptions.Producer,
         partitionKeyExtractorStrategy,
         partitionSelectorStrategy);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">The evaluation context</param>
        /// <param name="expression">The expression</param>
        public SingleExpressionEvaluator(IEvaluationContext context, string expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            this.expression = expression;
            this.context    = context;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// This property signs if an expression is ready to be evaluated,
        /// namely, all subexpression values are known
        /// </summary>
        /// <param name="evalContext">Evaluation context</param>
        /// <returns>True, if the expression is ready; otherwise, false</returns>
        public override bool ReadyToEvaluate(IEvaluationContext evalContext)
        {
            var result = evalContext.GetSymbolValue(SymbolName, ScopeSymbolNames, StartFromGlobal).ExprValue != null;

            if (!result)
            {
                AddError(FullSymbolName);
            }
            return(result);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">The evaluation context</param>
        /// <param name="expression">The expression</param>
        public SingleExpressionEvaluator(IEvaluationContext context, string expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            this.expression = expression;
            this.context = context;
        }
Ejemplo n.º 28
0
        /// Evaluate the operation against stack
        public void Eval(IEvaluationContext context, Stack <object> stack)
        {
            Type t = OperationHelper.ResolveType(context, _typeName);

            if (t == null)
            {
                throw new TypeLoadException("Failed to resolve type '" + _typeName + "'");
            }
            stack.Push(t);
        }
Ejemplo n.º 29
0
        public override Task <PromotionReward[]> EvaluatePromotionAsync(IEvaluationContext context)
        {
            foreach (var reward in Rewards)
            {
                reward.Promotion = this;
                reward.IsValid   = Condition == null || Condition(context);
            }

            return(Task.FromResult(Rewards.ToArray()));
        }
        public bool Evaluate(Check check, IEvaluationContext context)
        {
            ManagementObjectSearcher searcher = WmiHelper.RunWmiQuery(check.Value);

            if (searcher.Get().Count > 0)
            {
                return(true);
            }
            return(false);
        }
Ejemplo n.º 31
0
        public void ShouldEvaluateToFalse()
        {
            CertificateCheckEvaluator evaluator = new CertificateCheckEvaluator();
            Check check = new Check {
                Name = "Certficate", Value = "LocalMachine,My,CN=noExist"
            };
            IEvaluationContext nullContext = null;

            Assert.IsFalse(evaluator.Evaluate(check, nullContext));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// ((PromotionEvaluationContext)x).IsItemInProduct(ProductId)
        /// </summary>
        public override bool Evaluate(IEvaluationContext context)
        {
            var result = false;

            if (context is PromotionEvaluationContext promotionEvaluationContext)
            {
                result = promotionEvaluationContext.IsItemInProduct(ProductId);
            }

            return(result);
        }
        public override bool Evaluate(IEvaluationContext context)
        {
            var result = false;

            if (context is EvaluationContextBase evaluationContext)
            {
                result = UseMatchedCondition(evaluationContext.GeoZipCode);
            }

            return(result);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// ((PromotionEvaluationContext)x).IsItemsInStockQuantity(Exactly, Quantity, QuantitySecond)
        /// </summary>
        public override bool Evaluate(IEvaluationContext context)
        {
            var result = false;

            if (context is PromotionEvaluationContext promotionEvaluationContext)
            {
                result = promotionEvaluationContext.IsItemsInStockQuantityNew(CompareCondition, Quantity, QuantitySecond);
            }

            return(result);
        }
Ejemplo n.º 35
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     var p = stack.Pop();
     Type t = OperationHelper.ResolveType(context, _typeName);
     if (t == null)
         throw new TypeLoadException("Failed to resolve type '" + _typeName + "'");
     if (p==null)
         stack.Push(false);
     else
         stack.Push(t.IsAssignableFrom(p.GetType()));
 }
Ejemplo n.º 36
0
        public override bool IsSatisfiedBy(IEvaluationContext context)
        {
            var result = false;

            if (context is CustomerSegmentExpressionEvaluationContext evaluationContext)
            {
                return(evaluationContext.CustomerHasPropertyValues(this));
            }

            return(result);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// ((PromotionEvaluationContext)x).IsEveryone
        /// </summary>
        public override bool IsSatisfiedBy(IEvaluationContext context)
        {
            var result = false;

            if (context is PromotionEvaluationContext promotionEvaluationContext)
            {
                result = promotionEvaluationContext.IsEveryone;
            }

            return(result);
        }
        public bool CanRead(IEvaluationContext context, object target, string name)
        {
            var serviceType = ServiceFactoryResolver.GetServiceNameAndType(context, name, out var lookupName);

            if (serviceType != null)
            {
                return(target is IServiceExpressionContext context1 && context1.ContainsService(lookupName, serviceType));
            }

            return(target is IServiceExpressionContext context2 && context2.ContainsService(name));
        }
Ejemplo n.º 39
0
        public override bool Evaluate(IEvaluationContext context)
        {
            var result = false;

            if (context is PromotionEvaluationContext promotionEvaluationContext)
            {
                result = promotionEvaluationContext.IsRegisteredUser;
            }

            return(result);
        }
		public DynamicContentItem[] EvaluateItems(IEvaluationContext context)
		{
            var dynamicContext = context as DynamicContentEvaluationContext;
			if(context == null)
			{
				throw new ArgumentNullException("dynamicContext");
			}

            var retVal = new List<DynamicContentItem>();
            using (var repository = _repositoryFactory())
			{
                var publishings = repository.PublishingGroups.Include(x => x.ContentItems)
                                                       .Where(x => x.IsActive)
                                                       .Where(x => x.StoreId == dynamicContext.StoreId)
                                                       .Where(x => (x.StartDate == null || dynamicContext.ToDate >= x.StartDate) && (x.EndDate == null || x.EndDate >= dynamicContext.ToDate))
                                                       .Where(x => x.ContentPlaces.Any(y => y.ContentPlace.Name == dynamicContext.PlaceName))
                                                       .OrderBy(x => x.Priority)
                                                       .ToArray();

                //Get content items ids for publishings without ConditionExpression
                var contentItemIds = publishings.Where(x => x.ConditionExpression == null)
                                                .SelectMany(x => x.ContentItems)
                                                .Select(x => x.DynamicContentItemId)
                                                .ToList();
                foreach (var publishing in publishings.Where(x=>x.ConditionExpression != null))
                {
                    try
                    {
                        //Next step need filter assignments contains dynamicexpression
                        var condition = SerializationUtil.DeserializeExpression<Func<IEvaluationContext, bool>>(publishing.ConditionExpression);
                        if (condition(context))
                        {
                            contentItemIds.AddRange(publishing.ContentItems.Select(x=>x.DynamicContentItemId));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex);
                    }
                }

                foreach (var contentItemId in contentItemIds)
				{
					var contentItem = _dynamicContentService.GetContentItemById(contentItemId);
					retVal.Add(contentItem);
				}
			
			}

			return retVal.ToArray();
		}
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context">The evaluation context</param>
        /// <param name="expression">The expression</param>
        public MultipleExpressionEvaluator(IEvaluationContext context, string expression)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "evaluation context must be provided");
            }

            if (expression == null)
            {
                throw new ArgumentNullException("expression", "expression must be provided");
            }

            this.expression = expression;
            this.context = context;
        }
Ejemplo n.º 42
0
        /// Evaluate the operation against stack
        public void Eval(IEvaluationContext context, Stack<object> stack)
        {
            var o = OperationHelper.PopArray(stack, _paramCount);

            // Find a general object type
            Type parent = null;
            foreach (var o1 in o)
                parent = Utils.CommonBase(o1, parent);

            if (parent == null || parent == typeof(object))
                stack.Push(o);
            else
            {
                Array a = (Array)Activator.CreateInstance(parent.MakeArrayType(), o.Length);
                for (int i = 0; i < a.Length; ++i)
                    a.SetValue(o[i], i);
                stack.Push(a);
            }
        }
		public override PromotionReward[] EvaluatePromotion(IEvaluationContext context)
		{
			var retVal = new List<PromotionReward>();
			var promoContext = context as PromotionEvaluationContext;
			if (promoContext != null)
			{
				foreach (var entry in promoContext.PromoEntries)
				{
					var tag = entry.Attributes != null ? entry.Attributes["tag"] : null;
					var reward = new CatalogItemAmountReward
					{
						AmountType = RewardAmountType.Relative,
						Amount = _discountAmount,
						IsValid = !String.IsNullOrEmpty(tag) ? _tags.Contains(tag) : false,
						ProductId = entry.ProductId,
						Promotion = this
					};
				}
			}
			return retVal.ToArray();
		}
Ejemplo n.º 44
0
 /// <summary>
 /// Try to resolve typename to type. This is a helper function on top of <see cref="IEvaluationContext.FindType"/> that parses [] and ? suffix
 /// </summary>
 /// <param name="context"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static Type ResolveType(IEvaluationContext context, string name)
 {
     bool nullable = false;
     bool array = false;
     if (name.EndsWith("[]", StringComparison.Ordinal))
     {
         array = true;
         name = name.Substring(0, name.Length - 2);
     }
     if (name.EndsWith("?", StringComparison.Ordinal))
     {
         nullable = true;
         name = name.Substring(0, name.Length - 1);
     }
     Type t = context.FindType(name);
     if (t != null)
     {
         if (nullable)
             t = typeof(Nullable<>).MakeGenericType(t);
         if (array)
             t = t.MakeArrayType();
     }
     return t;
 }
Ejemplo n.º 45
0
		public override PromotionReward[] EvaluatePromotion(IEvaluationContext context)
		{
			var retVal = new List<PromotionReward>();
			var promoContext = context as PromotionEvaluationContext;
			if (promoContext == null)
			{
				throw new ArgumentException("context should be PromotionEvaluationContext");
			}

			//Check coupon
			var couponValid = (Coupons != null && Coupons.Any()) ? Coupons.Any(x=> String.Equals(x, promoContext.Coupon, StringComparison.InvariantCultureIgnoreCase)) : true;

			//deserealize dynamic condition
			var condition = SerializationUtil.DeserializeExpression<Func<IEvaluationContext, bool>>(PredicateSerialized);
			//deserealize rewards
			var rewards = JsonConvert.DeserializeObject<PromotionReward[]>(RewardsSerialized, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
			//Evaluate reward for all promoEntry in context
			foreach (var promoEntry in promoContext.PromoEntries)
			{
				//Set current context promo entry for evaluation
				promoContext.PromoEntry = promoEntry;
				foreach (var reward in rewards.Select(x=>x.Clone()))
				{
					reward.Promotion = this;
					reward.IsValid = couponValid && condition(promoContext);
					var catalogItemReward = reward as CatalogItemAmountReward;
					//Set productId for catalog item reward
					if (catalogItemReward != null && catalogItemReward.ProductId == null)
					{
						catalogItemReward.ProductId = promoEntry.ProductId;
					}
					retVal.Add(reward);
				}
			}
			return retVal.ToArray();
		}
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="context">The evaluation context</param>
 public SingleExpressionEvaluator(IEvaluationContext context)
 {
     this.context = context;
 }
Ejemplo n.º 47
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     string name = null;
     foreach (var option in _options)
     {
         object z;
         if (option.Name != null)
         {
             name = option.Name;
             if (context.TryGetValue(option.Name, out z))
             {
                 stack.Push(z);
                 return;
             }
         }
         else if (option.Expression != null)
         {
             option.Expression.Eval(context, stack);
             return;
         }
         else
         {
             stack.Push(option.Value);
             return;
         }
     }
     throw new KeyNotFoundException("Variable '"+name+"' is undefined");
 }
Ejemplo n.º 48
0
		/////////////////////////////////////////////////////////////////////////////
		/// <summary>
		/// Invokes a macro with an instance of IEvaluationContext which provides
		/// the text to be processed along with some information on where it came
		/// from
		/// </summary>
		/// <param name="evx"></param>
		/// <param name="newOutput"></param>
		/// <returns></returns>
		
		public string Evaluate( IEvaluationContext evx, bool newOutput )
		{
			using( new NMP.NmpMakeCurrent(nmp) ) {
				return nmp.Evaluate( evx, newOutput );
			}
		}
Ejemplo n.º 49
0
Archivo: Repl.cs Proyecto: vogon/nomic
 internal Repl(IReplView view, IEvaluationContext language)
 {
     this._view = view;
     this._language = language;
 }
Ejemplo n.º 50
0
        public override IEnumerable<TaxRate> CalculateRates(IEvaluationContext context)
        {
            var taxEvalContext = context as TaxEvaluationContext;
            if (taxEvalContext == null)
            {
                throw new NullReferenceException("taxEvalContext");
            }

            var retVal = GetTaxRates(taxEvalContext);
            return retVal;
        }
Ejemplo n.º 51
0
		/////////////////////////////////////////////////////////////////////////////
		
		public void MultipleEvaluate( IEvaluationContext evx )
		{
			nmp.MultileEvaluate( evx );
		}
Ejemplo n.º 52
0
 public abstract IEnumerable<TaxRate> CalculateRates(IEvaluationContext context);
		public PromotionResult EvaluatePromotion(IEvaluationContext context)
		{
			var now = DateTime.UtcNow;
			var promotions = _promotionService.GetActivePromotions();

			var promoContext = (PromotionEvaluationContext)context;

			var retVal = new PromotionResult();

			var rewards = promotions.SelectMany(x => x.EvaluatePromotion(context)).ToArray();

			//best shipment promotion
			var curShipmentAmount = promoContext.ShipmentMethodCode != null ? promoContext.ShipmentMethodPrice : 0m;
			var allShipmentRewards = rewards.OfType<ShipmentReward>().ToArray();
			EvaluteBestAmountRewards(curShipmentAmount, allShipmentRewards).ToList().ForEach(x => retVal.Rewards.Add(x));

			//best catalog item promotion
			var allItemsRewards = rewards.OfType<CatalogItemAmountReward>().ToArray();
			var groupRewards = allItemsRewards.GroupBy(x => x.ProductId).Where(x=>x.Key != null);
			foreach (var groupReward in groupRewards)
			{
				var item = promoContext.PromoEntries.FirstOrDefault(x => x.ProductId == groupReward.Key);
				if (item != null)
				{
					EvaluteBestAmountRewards(item.Price, groupReward.ToArray()).ToList().ForEach(x => retVal.Rewards.Add(x));
				}
			}
		
			//best order promotion 
			var cartSubtotalRewards = rewards.OfType<CartSubtotalReward>().Where(x => x.IsValid).OrderByDescending(x => x.Amount);
			var cartSubtotalReward = cartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault();
			if (cartSubtotalReward != null)
			{
				retVal.Rewards.Add(cartSubtotalReward);

				//Exlusive offer
				if (cartSubtotalReward.IsExclusive)
				{
					var itemRewards = retVal.Rewards.OfType<CatalogItemAmountReward>().ToList();
					for (var i = itemRewards.Count - 1; i >= 0; i--)
					{
						retVal.Rewards.Remove(itemRewards[i]);
					}
				}
			}
			var potentialCartSubtotalRewards = rewards.OfType<CartSubtotalReward>().Where(x => !x.IsValid).OrderByDescending(x => x.Amount);
			var potentialCartSubtotalReward = potentialCartSubtotalRewards.FirstOrDefault(x => !string.IsNullOrEmpty(x.Coupon)) ?? cartSubtotalRewards.FirstOrDefault();
			if (potentialCartSubtotalReward != null && cartSubtotalReward != null)
			{
				if (potentialCartSubtotalReward.Amount > cartSubtotalReward.Amount)
				{
					retVal.Rewards.Add(potentialCartSubtotalReward);
				}
			}
			else if (potentialCartSubtotalReward != null)
			{
				retVal.Rewards.Add(potentialCartSubtotalReward);
			}


			//Gifts
			rewards.OfType<GiftReward>().ToList().ForEach(x => retVal.Rewards.Add(x));

			//Special offer
			rewards.OfType<SpecialOfferReward>().ToList().ForEach(x => retVal.Rewards.Add(x));

			return retVal;
		}
 internal static int CalculateSignatureLength(IEvaluationContext context)
 {
     PAC_SIGNATURE_DATA_SignatureType_Values signatureType = (PAC_SIGNATURE_DATA_SignatureType_Values)context.Variables["SignatureType"];
     return PacSignatureData.CalculateSignatureLength(signatureType);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="stream">Stream of tokens</param>
 /// <param name="context">Evaluation context</param>
 public ExpressionParser(ITokenStream stream, IEvaluationContext context)
 {
     this.stream = stream;
     this.context = context;
     GetNextToken();
 }
Ejemplo n.º 56
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     stack.Push(_value);
 }
Ejemplo n.º 57
0
		/////////////////////////////////////////////////////////////////////////////
		
		public void MultileEvaluate( IEvaluationContext evx )
		{
			// ******
			//
			// EvalLock() will throw an exception if this instance of NMP is already
			// evaluating something, it also calls Restore()/Save() for our thread
			// data
			//
			using( new EvalLock( this ) ) {
				try {
					using( var input = gc.GetMasterParseReader( new ParseStringReader( evx.Text, evx.FileName ) ) ) {
						
						if( null == multileEvalOutput ) {
							multileEvalOutput = new MasterOutput( gc );
						}
		
						// ******
						var mir = new MIR( null, input, "Root" );
						
						using( Get<InvocationContext>().Init( mir ) ) {
							SetMacroProcessorOutputInstance( multileEvalOutput );
							Scanner( input, multileEvalOutput );
							SetMacroProcessorOutputInstance( null );
						}
		
					}
				}
				finally {
				}
			}
		}
Ejemplo n.º 58
0
        /// Evaluate the operation against stack
        public void Eval(IEvaluationContext context, Stack<object> stack)
        {
            object[] p = OperationHelper.PopArray(stack, _paramCount);

            if (!_thisCall && !_id.Contains(".") && !_isProperty)
            {
                stack.Push(context.CallExternal(_id, p));
                return;
            }

            // ID is smth like x.y.z where we have no idea whether x is namespace,type, or object name. So we split it
            // and ask
            var parts = (!_id.Contains(".") && !string.IsNullOrEmpty(_id) && _paramCount != 0 && _isProperty)?((_id+".").Split('.')):_id.Split('.');

            IEnumerable<TypeObjectPair> typeAndObjects = null;
            if (_thisCall)
            {
                var o=stack.Pop();
                typeAndObjects = new TypeObjectPair[] { new TypeObjectPair(o.GetType(), o) };
            }

            object sub;
            bool success = false;
            for (int i=0;i<parts.Length;++i)
            {
                string currentPart = parts[i];
                if (typeAndObjects == null)
                {
                    string tn = string.Join(".", parts, 0, i + 1);
                    if (string.IsNullOrEmpty(tn))
                        typeAndObjects = context.GetNonameObjects();
                    else
                    {
                        if (context.TryGetExternal(tn, out sub))
                        {
                            success = true;
                            typeAndObjects = (sub == null) ? null : new[] {new TypeObjectPair(sub.GetType(), sub)};
                        }
                        else
                        {
                            var t = context.FindType(tn);
                            if (t != null)
                            {
                                typeAndObjects = new[] { new TypeObjectPair(t, null) };
                                success = true;
                            }
                        }
                    }
                }
                else
                {
                    success = false;
                    foreach (var to in typeAndObjects)
                    {
                        if (_isProperty || i != parts.Length - 1)
                            success = Utils.TryGetProperty(to.Object, to.Type, currentPart, (i == parts.Length - 1) ? p : null, context.AccessPrivate,out sub);
                        else
                            success = Utils.TryCallMethod(to.Object, to.Type, currentPart, (i == parts.Length - 1) ? p : null, context.AccessPrivate, out sub);
                        if (success)
                        {
                            typeAndObjects = null;
                            if (!object.ReferenceEquals(sub, null))
                                typeAndObjects = new[] {new TypeObjectPair(sub.GetType(), sub)};
                            break;
                        }
                    }
                    if (!success)
                    {
                        // Last possible chance for COM objects where reflection does not work, but calling might!
                        if (i==parts.Length-1)
                        {
                            foreach (var to in typeAndObjects)
                            {
                                if (to.Object==null)
                                    continue;

                                if (_isProperty)
                                {
                                    if (p.Length == 0)
                                    {
                                        stack.Push(Utils.GetProperty(to.Object, currentPart));
                                        return;
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        stack.Push(Utils.CallMethod(to.Object, currentPart, p));
                                    }
                                    catch(Exception e)
                                    {
                                        var comex = e as System.Runtime.InteropServices.COMException;
                                        var miex = e as MissingMethodException;
                                        if (miex != null || (comex != null && ((uint)comex.ErrorCode == 0x80020006u || (uint)comex.ErrorCode == 0x80020005u)))
                                        {
                                            if (currentPart.StartsWith("set_", StringComparison.OrdinalIgnoreCase) && p.Length == 1)
                                            {
                                                Utils.SetPropertySimple(to.Object, currentPart.Substring(4), p[0]);
                                                stack.Push(null);
                                                return;
                                            }
                                            if (currentPart.StartsWith("get_", StringComparison.OrdinalIgnoreCase) && p.Length == 0)
                                            {
                                                stack.Push(Utils.GetProperty(to.Object, currentPart.Substring(4)));
                                                return;
                                            }
                                        }
                                        if (e is System.Reflection.TargetInvocationException && e.InnerException!=null)
                                            Utils.Rethrow(e.InnerException);
                                        Utils.Rethrow(e);
                                    }
                                    return;
                                }
                            }
                        }
                        throw new MissingMemberException("Failed to resolve '" + currentPart + "' with "+p.Length+" arguments");
                    }
                }
            }
            if (!success)
                throw new MissingMemberException("Failed to resolve '" + _id + "' with " + p.Length + " arguments");
            if (typeAndObjects==null)
                stack.Push(null);
            else
                foreach (var o in typeAndObjects)
                {
                    stack.Push(o.Object);
                    break;
                }
        }
Ejemplo n.º 59
0
 /// Evaluate the operation against stack
 public void Eval(IEvaluationContext context, Stack<object> stack)
 {
     stack.Pop();
 }
 /// <summary>
 /// Customized length calculator of ApplicationData, called by Channel.
 /// This method's name is written in ApplicationData's Size attribute. 
 /// </summary>
 /// <param name="context">Channel's context.</param>
 /// <returns>ApplicationData's length.</returns>
 // this method is called by Channel.
 internal static int CalculateApplicationDataLength(IEvaluationContext context)
 {
     _ACE_HEADER header = (_ACE_HEADER)context.Variables["Header"];
     _SID sid = (_SID)context.Variables["Sid"];
     return DtypUtility.CalculateApplicationDataLength(header, sid);
 }