Пример #1
0
        private static void Strategy()
        {
            #region Strategy

            decimal a = 10;
            decimal b = 5;

            CalculatorContext calculatorContext = new CalculatorContext();
            calculatorContext.SetStrategy(new StrategyAddition());
            Console.WriteLine("Resultado: " + calculatorContext.Calculate(a, b));

            calculatorContext.SetStrategy(new StrategySubtraction());
            Console.WriteLine("Resultado: " + calculatorContext.Calculate(a, b));

            calculatorContext.SetStrategy(new StrategyMultiplication());
            Console.WriteLine("Resultado: " + calculatorContext.Calculate(a, b));

            calculatorContext.SetStrategy(new StrategyDivision());
            Console.WriteLine("Resultado: " + calculatorContext.Calculate(a, b));

            calculatorContext.SetStrategy(new StrategyExponentiation());
            Console.WriteLine("Resultado: " + calculatorContext.Calculate(a, b));

            #endregion Strategy
        }
Пример #2
0
        public MainViewModel()
        {
            CalculatorContext context = new CalculatorContext();

            _operations = new Operations();
            _repository = new NumberRepository(context);
        }
Пример #3
0
 public SearchHistoryService(
     CalculatorContext context,
     ICityService cityService)
 {
     this.context     = context;
     this.cityService = cityService;
 }
Пример #4
0
        public void TestNinject()
        {
            // Arrange
            List <string>  mylist = new List <string>(new string[] { "121556550", "15589455452", "2254564555565552", "5554525455454554565" });
            StandardKernel kernel = new StandardKernel();

            // Load Modules
            // Assemblies of the current project (Assemblies in Unit Test).
            //kernel.Load(Assembly.GetExecutingAssembly());

            // Assemblies of the solution (Assemblies in all projects).
            kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

            CalculatorContext calculatorContext = null;

            try
            {
                // Gets a instance of the specified service.
                SumStrategy      objCalculate  = kernel.Get <SumStrategy>();      //("Sum");
                MultipleStrategy objCalculate2 = kernel.Get <MultipleStrategy>(); // ("Multiple");


                // Act: Inject
                calculatorContext = new CalculatorContext(objCalculate, objCalculate2);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }


            // Assert
            Assert.AreEqual(calculatorContext.Sum(mylist), "5556780035721132119");
        }
Пример #5
0
        private async Task EnsureAssociatedProductsAreLoaded(Product product, CalculatorContext context)
        {
            var options = context.Options;

            if (context.AssociatedProducts == null)
            {
                // Associated products have not been preloaded unfortunately. Get 'em here for this particular product.
                var searchQuery = new CatalogSearchQuery()
                                  .PublishedOnly(true)
                                  .HasStoreId(options.Store.Id)
                                  .HasParentGroupedProduct(product.Id);

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                context.AssociatedProducts = (await searchResult.GetHitsAsync()).OrderBy(x => x.DisplayOrder).ToList();
            }

            if (options.ChildProductsBatchContext == null && context.AssociatedProducts.Any())
            {
                // No batch context given for the listing batch, so create one for associated products of this particular product.
                options.ChildProductsBatchContext = _productService.CreateProductBatchContext(context.AssociatedProducts, options.Store, options.Customer, false);
            }

            // Continue pipeline with AssociatedProductsBatchContext
            options.BatchContext = options.ChildProductsBatchContext;
        }
Пример #6
0
 public CalculatorCostService(CalculatorContext context, ICityService cityService, IModuleService moduleService, ISearchHistoryService searchHistoryService)
 {
     this.context              = context;
     this.cityService          = cityService;
     this.moduleService        = moduleService;
     this.searchHistoryService = searchHistoryService;
 }
Пример #7
0
        public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next)
        {
            var product = context.Product;
            var options = context.Options;
            // Ignore tier prices of bundle items (BundlePerItemPricing).
            var processTierPrices = !options.IgnoreTierPrices && !options.IgnoreDiscounts && product.HasTierPrices && context.BundleItem?.Item == null;

            if (processTierPrices)
            {
                var tierPrices = await context.GetTierPricesAsync();

                // Put minimum tier price to context because it's required for discount calculation.
                context.MinTierPrice = GetMinimumTierPrice(product, tierPrices, context.Quantity);

                if (context.Options.DetermineLowestPrice && !context.HasPriceRange)
                {
                    context.HasPriceRange = tierPrices.Any() && !(tierPrices.Count == 1 && tierPrices.First().Quantity <= 1);
                }
            }

            // Process the whole pipeline. We need the result of discount calculation.
            await next(context);

            if (processTierPrices && context.MinTierPrice.HasValue)
            {
                // Apply the minimum tier price if it achieves a lower price than the discounted FinalPrice.
                context.FinalPrice = Math.Min(context.FinalPrice, context.MinTierPrice.Value);
            }
        }
Пример #8
0
        public override CalculatorContext Invoke(CalculatorContext ctx)
        {
            var newCtx = ctx.Copy();

            newCtx.Reset();
            return(newCtx);
        }
Пример #9
0
            protected internal override void Sub(CalculatorContext context, Stack <string> stack)
            {
                Calculator ctxt = context.Owner;

                if (stack.Count >= 2)
                {
                    CalculatorState endState = context.State;

                    context.ClearState();

                    try
                    {
                        ctxt.Sub();
                    }
                    finally
                    {
                        context.State = endState;
                    }
                }
                else
                {
                    context.State.Exit(context);
                    context.State = Map1.ErrorTuple;
                    context.State.Entry(context);
                }

                return;
            }
Пример #10
0
        static void Main(string[] args)
        {
            while (true)
            {
                context = new CalculatorContext();
                Console.WriteLine("Hello, welcome to the Strategy Pattern PoC.");
                Console.WriteLine("Please, select your Calculation method:");
                Console.WriteLine(Environment.NewLine + "1 - Addition");
                Console.WriteLine(Environment.NewLine + "2 - Subtraction");
                Console.WriteLine(Environment.NewLine + "3 - Multiplication");
                var inputChoice = Convert.ToInt32(Console.ReadLine());
                var strategy    = context.GetCorrectStrategy(inputChoice);
                if (strategy == "AdditionStrategy")
                {
                    context.SetStrategy(new AdditionStrategy());
                }
                else if (strategy == "SubtractionStrategy")
                {
                    context.SetStrategy(new SubtractionStrategy());
                }
                else if (strategy == "MultiplicationStrategy")
                {
                    context.SetStrategy(new MultiplicationStrategy());
                }

                Console.WriteLine("Please, enter enter in the first number");
                var firstNumber = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Please, enter enter in the second number");
                var secondNumber = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Answer:");
                Console.WriteLine(context.ExecuteStrategy(firstNumber, secondNumber));
            }
        }
Пример #11
0
 public List <Operators> GetOperators()
 {
     using (var context = new CalculatorContext())
     {
         return(context.Operators.ToList());
     }
 }
Пример #12
0
        public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next)
        {
            if (context.Options.IgnoreOfferPrice)
            {
                // Ignore offer price for this calculation.
                await next(context);

                return;
            }

            var product = context.Product;

            if (product.SpecialPrice.HasValue)
            {
                // Check date range.
                var now  = DateTime.UtcNow;
                var from = product.SpecialPriceStartDateTimeUtc;
                var to   = product.SpecialPriceEndDateTimeUtc;

                if ((from == null || now >= from) && (to == null || now <= to))
                {
                    context.OfferPrice = product.SpecialPrice;
                    context.FinalPrice = product.SpecialPrice.Value;
                }
            }

            await next(context);
        }
Пример #13
0
            protected internal override void Enter(CalculatorContext context, string value)
            {
                Calculator ctxt = context.Owner;

                if (double.TryParse(value, out double _))
                {
                    context.State.Exit(context);
                    context.ClearState();

                    try
                    {
                        ctxt.Push(value);
                    }
                    finally
                    {
                        context.State = Map1.Calculate;
                        context.State.Entry(context);
                    }
                }
                else
                {
                    context.State.Exit(context);
                    context.State = Map1.ErrorNumeric;
                    context.State.Entry(context);
                }

                return;
            }
Пример #14
0
 public HomeController(CalculatorContext dbContext,
                       UserManager <AspNetUsers> userManager,
                       SignInManager <AspNetUsers> signInManager)
 {
     _dbContext     = dbContext;
     _userManager   = userManager;
     _signInManager = signInManager;
 }
Пример #15
0
 public List <Operation> GetQueue()
 {
     using (var db = new CalculatorContext(configuration.DbConnectionString))
     {
         return(db.Operations.AsNoTracking().OrderBy(q => q.OperationId)
                .ToArray().Select(source => dtoOperationMapper.Map(source)).ToList());
     }
 }
Пример #16
0
        public void Setup()
        {
            var calculatorContext = new CalculatorContext();

            _calculatorHelper = new CalculatorHelper();
            _calculator       = new Calculator(calculatorContext);
            _calculatorHelper.SetupCalculator(_calculator);
        }
Пример #17
0
 protected internal virtual void Default(CalculatorContext context)
 {
     throw (
               new statemap.TransitionUndefinedException(
                   "State: " +
                   context.State.Name +
                   ", Transition: " +
                   context.GetTransition()));
 }
Пример #18
0
 public CalculationsController(
     ITaxCalculatorFactory factory,
     CalculatorContext context,
     ILogger <CalculationsController> logger)
 {
     _factory = factory;
     _context = context;
     _logger  = logger;
 }
Пример #19
0
            protected internal override void Enter(CalculatorContext context, string value)
            {
                context.State.Exit(context);
                context.State = Map1.Enter;
                context.State.Entry(context);


                return;
            }
Пример #20
0
        public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next)
        {
            var product = context.Product;

            if (product.ProductType != ProductType.GroupedProduct)
            {
                // Proceed with pipeline and omit this calculator, it is made for grouped products only.
                await next(context);

                return;
            }

            var options = context.Options;

            if (options.IgnoreGroupedProducts)
            {
                await next(context);

                return;
            }

            await EnsureAssociatedProductsAreLoaded(product, context);

            if (context.AssociatedProducts.Count == 0)
            {
                // No children, get out.
                return;
            }

            CalculatorContext lowestPriceCalculation = null;

            if (options.DetermineLowestPrice && context.AssociatedProducts.Count > 1)
            {
                foreach (var associatedProduct in context.AssociatedProducts)
                {
                    // Get the final price of associated product
                    var childCalculation = await CalculateChildPriceAsync(associatedProduct, context);

                    if (lowestPriceCalculation == null || childCalculation.FinalPrice < lowestPriceCalculation.FinalPrice)
                    {
                        // Set the lowest price calculation
                        lowestPriceCalculation = childCalculation;
                    }
                }

                lowestPriceCalculation.HasPriceRange = true;
            }
            else
            {
                // Get the final price of first associated product
                lowestPriceCalculation = await CalculateChildPriceAsync(context.AssociatedProducts.First(), context);
            }

            // Copy data from child context to this context
            lowestPriceCalculation.CopyTo(context);
        }
Пример #21
0
 public void AddToQueue(Operation operation)
 {
     using (var db = new CalculatorContext(configuration.DbConnectionString))
     {
         var dbOperation = dbOperationMapper.Map(operation);
         dbOperation.CalculatorId = configuration.CalculatorId;
         db.Operations.Add(dbOperation);
         db.SaveChanges();
     }
 }
Пример #22
0
        protected override ICalculatorState OnClear(Clear clear)
        {
            if (_hasNewOperand)
            {
                _tempCtx = clear.Invoke(_tempCtx);
                return(this);
            }

            return(new OperandState(clear.Invoke(Ctx)));
        }
Пример #23
0
 public HistoricalViewModel()
 {
     _id               = UserService.UserService.LoggedInUserId;
     _context          = new CalculatorContext();
     _numberRepository = new NumberRepository(_context);
     _numbersList      = new ObservableCollection <string>();
     numbersList       = new List <string>();
     numbersList       = _numberRepository.GetUserNumbersList(_id);
     numbersList.ToList().ForEach(_numbersList.Add);
 }
Пример #24
0
        public double CalculateFor(Coupon coupon, double totalAmount)
        {
            if (totalAmount < coupon.MinimumPurchaseAmount)
            {
                return(default(double));
            }

            var discountCalculatorContext = new CalculatorContext(coupon.DiscountType, coupon.AmountOfDiscount, totalAmount);

            return(discountCalculatorContext.Calculate());
        }
        public void IsSet()
        {
            var order = new OrderCarrier();

            using (CalculatorContext.Use(order))
            {
                Assert.Same(order, CalculatorContext.GetCurrentOrderCarrier());
            }

            Assert.Null(CalculatorContext.GetCurrentOrderCarrier());
        }
Пример #26
0
        private async Task ProcessAnnualSalaryStrategy(List <EmployeeEntity> entities)
        {
            var calculatorContext = new CalculatorContext();

            foreach (var item in entities)
            {
                var type = (AnnualSalaryStrategy.CalculationTypes)System.Enum
                           .Parse(typeof(AnnualSalaryStrategy.CalculationTypes), item.ContractTypeName);
                item.CalculatedAnnualSalary = await calculatorContext.calculators[type].CalculateAnnualSalaryAsync(item);
            }
        }
Пример #27
0
        public void Calculate(CalculatorContext memory)
        {
            //memory.PopNumber();
            if (memory.Count() < 2)
            {
                throw new SyntaxErrorException();
            }
            var exp1 = memory.PopNumber();
            var exp2 = memory.PopNumber();

            memory.PushNumber(new Number(exp2.Value * exp1.Value));
        }
        public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next)
        {
            var      product         = context.Product;
            var      bundleItem      = context.BundleItem;
            Discount appliedDiscount = null;

            if (bundleItem?.Item != null)
            {
                var bi = bundleItem.Item;
                if (bi.Discount.HasValue && bi.BundleProduct.BundlePerItemPricing)
                {
                    appliedDiscount = new Discount
                    {
                        UsePercentage      = bi.DiscountPercentage,
                        DiscountPercentage = bi.Discount.Value,
                        DiscountAmount     = bi.Discount.Value
                    };

                    context.AppliedDiscounts.Add(appliedDiscount);
                    var discountAmount = appliedDiscount.GetDiscountAmount(context.FinalPrice);
                    context.FinalPrice -= discountAmount;
                }
            }
            else if (!context.Options.IgnoreDiscounts && !product.CustomerEntersPrice)
            {
                // Don't calculate when customer entered price or discounts should be ignored in any case.
                var applicableDiscounts = await GetApplicableDiscounts(product, context);

                if (applicableDiscounts.Any())
                {
                    appliedDiscount = applicableDiscounts.GetPreferredDiscount(context.FinalPrice);

                    if (appliedDiscount != null)
                    {
                        context.AppliedDiscounts.Add(appliedDiscount);
                        var discountAmount = appliedDiscount.GetDiscountAmount(context.FinalPrice);
                        context.FinalPrice -= discountAmount;
                    }
                }
            }

            // Percentage discount on minimum tier price.
            if (!context.Options.IgnorePercentageDiscountOnTierPrices &&
                context.MinTierPrice.HasValue &&
                context.MinTierPrice != decimal.Zero &&
                appliedDiscount != null &&
                appliedDiscount.UsePercentage)
            {
                context.FinalPrice -= appliedDiscount.GetDiscountAmount(context.MinTierPrice.Value);
            }

            await next(context);
        }
        public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next)
        {
            if (!context.Options.DetermineLowestPrice)
            {
                // Proceed with pipeline and omit this calculator, it is made for lowest price calculation only.
                await next(context);

                return;
            }

            // Process the whole pipeline with maximum quantity to get the minimum tier price applied.
            context.Quantity = int.MaxValue;
            await next(context);

            // Get lowest possible price.
            var product     = context.Product;
            var lowestPrice = context.FinalPrice;
            var forceApply  = false;

            if (product.LowestAttributeCombinationPrice.HasValue && product.LowestAttributeCombinationPrice.Value < lowestPrice)
            {
                lowestPrice = product.LowestAttributeCombinationPrice.Value;
            }

            if (lowestPrice == decimal.Zero && product.Price == decimal.Zero)
            {
                // Do not display 0 as lowest price.
                forceApply  = true;
                lowestPrice = product.LowestAttributeCombinationPrice ?? decimal.Zero;
            }

            // Apply lowest price.
            if (lowestPrice < context.FinalPrice || forceApply)
            {
                context.FinalPrice = lowestPrice;
            }

            context.LowestPrice = context.FinalPrice;

            // Check whether the product has a price range.
            if (!context.HasPriceRange)
            {
                context.HasPriceRange = product.LowestAttributeCombinationPrice.HasValue;
            }

            if (!context.HasPriceRange)
            {
                var attributes = await context.Options.BatchContext.Attributes.GetOrLoadAsync(product.Id);

                context.HasPriceRange = attributes.Any(x => x.ProductVariantAttributeValues.Any(y => y.PriceAdjustment != decimal.Zero));
            }
        }
Пример #30
0
 public void RemoveOperationFromQueueByOperationId(int operationId)
 {
     using (var db = new CalculatorContext(configuration.DbConnectionString))
     {
         var dbOperation = db.Operations.FirstOrDefault(x => x.OperationId == operationId);
         if (dbOperation == null)
         {
             return;
         }
         db.Operations.Remove(dbOperation);
         db.SaveChanges();
     }
 }
 public int Calculate(CalculatorContext context)
 {
     return context.Calculator.Operation(context.Operator, context.Left, context.Right);
 }