Ejemplo n.º 1
0
        public IActionResult Calculate(CalculateModel Model)
        {
            var result = new CalculateResultModel();

            // validate
            var value1 = 0;

            if (int.TryParse(Model.Value1, out value1) == false)
            {
                result.errorFlg     = true;
                result.errorMessage = "value1 is number only";
                return(Json(result));
            }

            var value2 = 0;

            if (int.TryParse(Model.Value2, out value2) == false)
            {
                result.errorFlg     = true;
                result.errorMessage = "value2 is number only";
                return(Json(result));
            }

            result.Result = value1 + value2;
            return(Json(result));
        }
 public IActionResult Index(CalculateModel value)
 {
     if (ModelState.IsValid)
     {
         if (value.Operation == "Sum")
         {
             ViewBag.Result = value.Add().ToString();
         }
         else if (value.Operation == "Subtraction")
         {
             ViewBag.Result = value.Sub().ToString();
         }
         else if (value.Operation == "Multiplication")
         {
             ViewBag.Result = value.Mul().ToString();
         }
         else if (value.Operation == "Divisioin")
         {
             ViewBag.Result = value.Div().ToString();
         }
     }
     else
     {
         ViewBag.Result = "Enter operation correctly";
     }
     return(View());
 }
Ejemplo n.º 3
0
        public IActionResult Calculate(string textAreaNumber)
        {
            CalculateModel model = new CalculateModel();

            if (string.IsNullOrEmpty(textAreaNumber))   //沒有輸入
            {
                model.Message = "請輸入數字";
                return(Json(model));
            }

            textAreaNumber = textAreaNumber.Trim();
            var stringArray = textAreaNumber.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);     //切空白

            double[] inputNumbers = new double[stringArray.Length];

            for (int i = 0; i < inputNumbers.Length; i++)
            {
                Console.WriteLine(stringArray[i]);
                if (!Double.TryParse(stringArray[i], out inputNumbers[i])) //轉成Double
                {
                    model.Message = "錯誤,請輸入實數";                            //不符合格式
                    return(Json(model));
                }
            }

            model.Add(inputNumbers);    //加入Model

            return(Json(model));
        }
Ejemplo n.º 4
0
        public CalculateModel Calculate(DateTime start, DateTime end, int countryId)
        {
            var limitSetting = _settingRepo.Table.FirstOrDefault(m => m.Key == ReservationLimitKey);

            if (limitSetting == null)
            {
                throw new Exception($"{ReservationLimitKey} setting cannot found.");
            }
            int limit             = int.Parse(_settingRepo.Table.FirstOrDefault(m => m.Key == ReservationLimitKey).Value);
            var penaltyFeeSetting = _settingRepo.Table.FirstOrDefault(m => m.Key == PenaltyFeeKey);

            if (penaltyFeeSetting == null)
            {
                throw new Exception($"{PenaltyFeeKey} setting cannot found.");
            }
            int penaltyFee = int.Parse(penaltyFeeSetting.Value);
            var country    = _countryRepo.Table.Include("SpecialDays").Include("OffDaysOfWeek").FirstOrDefault(m => m.Id == countryId);

            var retVal = new CalculateModel(limit, penaltyFee, country.Currency);

            var offDays     = country.OffDaysOfWeek.Select(m => m.DayOfWeek);
            var specialDays = country.SpecialDays.Select(m => m.SpecialDate);

            var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
                        .Select(offset => start.AddDays(offset))        //all dates between start and end ones
                        .Where(day => !offDays.Contains(day.DayOfWeek)) //exclude off days
                        .Select(m => m.Date)                            //get all as only date format without time
                        .Where(m => !specialDays.Contains(m));          //subtract special days

            int totalDayCount = dates.Count();

            retVal.TotalDayCount = totalDayCount;
            return(retVal);
        }
Ejemplo n.º 5
0
        private async void CalculateButton_Click(object sender, EventArgs e)
        {
            try
            {
                string income   = this.income.Text;
                string expenses = expense.Text;


                //We check for null
                if (string.IsNullOrEmpty(income))
                {
                    MessageBox.Show($"Indkomst må ikke være tom", $"Du har ikke angivet en indkomst", MessageBoxButtons.OK);
                    throw new NullReferenceException($"Income cannot be null"); // Consider to remove - so you have option to put in. Right now it breaks.
                }

                if (string.IsNullOrEmpty(expenses))
                {
                    MessageBox.Show($"Udgift må ikke være tom", $"Du har ikke angivet en udgift", MessageBoxButtons.OK);
                    throw new NullReferenceException($"Expense cannot be null");
                }


                //Let's get results
                CalculateModel costResponse = await Handler.Calculate(Convert.ToDecimal(income),
                                                                      Convert.ToDecimal(expenses), Convert.ToDateTime(untilDate?.Value));

                FormMapping(costResponse);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
Ejemplo n.º 6
0
        public IActionResult Calculate(CalculateModel calculateModel)
        {
            if (!this.ModelState.IsValid)
            {
                calculateModel.Message = "invalid";
            }
            else
            {
                try
                {
                    DateTime dt = new DateTime(calculateModel.Year.GetValueOrDefault(0),
                                               calculateModel.Month.GetValueOrDefault(0),
                                               calculateModel.Day.GetValueOrDefault(0)
                                               );


                    DayOfWeek dow = dt.DayOfWeek;
                    calculateModel.Message = dow.ToString();
                }
                catch (ArgumentException ex)
                {
                    calculateModel.Message = ex.Message;
                }
            }

            return(View("Index", calculateModel));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> AllCalculates(int?Month)
        {
            if (_signInManager.Context.User.Identity.IsAuthenticated)
            {
                if (HttpContext.User.IsInRole("Payrole Specialist"))
                {
                    await Initializer.InitialLayout("Payrole Specialist", ViewBag, _db, _signInManager, "All");

                    if (Month == null)
                    {
                        Month = DateTime.Now.Month;
                    }
                    List <Calculate> calculates = await _db.Calculates
                                                  .Where(c => c.CalculateDate.Month == Month)
                                                  .Include(c => c.Employee)
                                                  .ToListAsync();

                    CalculateModel calculateModel = new CalculateModel
                    {
                        Calculates = calculates,
                        Month      = Convert.ToInt32(Month)
                    };
                    return(View(calculateModel));
                }
            }
            return(RedirectToAction("Forbidden", "Error"));
        }
        public async Task <decimal> GetPremium(CalculateModel calculateModel)
        {
            string premiumJobj = await _httpDataService.GetDataPostAsync("calculations", calculateModel);

            PremiumResponse premiumResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <PremiumResponse>(premiumJobj);

            return(premiumResponse.Premium);
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Calculate(CalculateModel model)
        {
            var taxAmount = await _apiClient.Client.CalculateAsync(Convert.ToDouble(model.Salary), model.PostalCode);

            model.TaxAmount = taxAmount;

            return(View(model));
        }
Ejemplo n.º 10
0
        public CalculateViewModel GetDeliveryCostPage(CalculateViewModel viewModel)
        {
            var model = new CalculateModel(viewModel, _deliveryCostCalculator, _config);

            model.CalculateDeliveryCost();

            return(model.ViewModel);
        }
Ejemplo n.º 11
0
        public void Calculation_Profit()
        {
            CalculateModel model = new CalculateModel {
                Income = 1, Expenses = 1
            };

            Assert.AreEqual(0, model.TotalProfit);
        }
        public void GetCurrentSpeedTest_NegetivValues()
        {
            CalculateModel model = new CalculateModel();

            var actual   = model.GetCurrentSpeed("-20", "-2");
            var expected = 10.0M;

            Assert.AreEqual(actual, expected);
        }
        public void GetCurrentSpeedTest_NotANumber()
        {
            CalculateModel model = new CalculateModel();

            var actual   = model.GetCurrentSpeed("20m", "2h");
            var expected = -1.0M;

            Assert.AreEqual(actual, expected);
        }
        public void GetCurrentSpeedTest_EmtyString()
        {
            CalculateModel model = new CalculateModel();

            var actual   = model.GetCurrentSpeed("20", "");
            var expected = -1.0M;

            Assert.AreEqual(actual, expected);
        }
Ejemplo n.º 15
0
        public void Calculation_IncomeAverage_Form_DifferentDay()
        {
            CalculateModel r = new CalculateModel {
                Income = Convert.ToDecimal(_income), Expenses = Convert.ToDecimal(_expense), UntilDate = DateTime.Now, DaysInMonth = 30.4375
            };
            string vI = r.IncomeAverage.ToString("C");

            Assert.AreEqual("29.902,12 kr.", vI);
        }
Ejemplo n.º 16
0
        public void Calculation_IncomeAverage_Form()
        {
            var r = new CalculateModel {
                Income = Convert.ToDecimal(_income), Expenses = Convert.ToDecimal(_expense), UntilDate = DateTime.Now, DaysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
            };
            string vI = r.IncomeAverage.ToString("C");


            Assert.AreEqual("29.472,31 kr.", vI);
        }
Ejemplo n.º 17
0
 public int GetResult(CalculateModel model)
 {
     return(model.CarType switch
     {
         CarType.Car => GetCarCustomValue(model.FuelType, model.EngineVolume, model.Price, model.Year),
         CarType.Truck => GetTruckCustomValue(model.Price, model.Year, model.EngineVolume, model.FuelWeight),
         CarType.Bus => GetBusCustomValue(model.Price, model.Year, model.EngineVolume, model.FuelType),
         CarType.Bike => GetBikeCustomValue(model.Price, model.Year, model.EngineVolume),
         _ => throw new NotImplementedException()
     });
Ejemplo n.º 18
0
        public IActionResult Index()
        {
            DateTime       dt             = DateTime.Now;
            CalculateModel calculateModel = new CalculateModel();

            calculateModel.Message = "Bitte geben Sie ein Datum ein.";
            calculateModel.Day     = dt.Day;
            calculateModel.Month   = dt.Month;
            calculateModel.Year    = dt.Year;
            return(View("Index", calculateModel));
        }
Ejemplo n.º 19
0
 public ActionResult Calculate(string id, CalculateModel mData)
 {
     try {
         var patientID = id;
         mData.TotalPayment = _paymentService.GetTotalPaymentByPatientID(patientID,
                                                                         mData.StartDate, mData.EndDate);
         mData.PatientID = patientID;
         return(View(mData));
     }
     catch (Exception) {
         return(View());
     }
 }
Ejemplo n.º 20
0
 private void FormMapping(CalculateModel r)
 {
     try
     {
         incomeValue.Text  = r.IncomeAverage.ToString("C");
         expenseValue.Text = r.ExpensesAverage.ToString("C");
         profit.Text       = r.ProfitAverage.ToString("C");
         savings.Text      = r.SavingsTotalRate.ToString("P");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
Ejemplo n.º 21
0
 public void SetCacheValue(string key, CalculateModel model)
 {
     if (_memoryCache.TryGetValue(key, out IEnumerable <string> collectionValue))
     {
         var queue = new FixedSizedQueue <string>(TypesConstants.QueueSize, collectionValue);
         queue.Enqueue(SetMemoryValue(model));
         _memoryCache.Set(key, queue);
     }
     else if (_memoryCache.TryGetValue(key, out string value))
     {
         var queue = new FixedSizedQueue <string>(TypesConstants.QueueSize, new List <string>()
         {
             value
         });
         queue.Enqueue(SetMemoryValue(model));
         _memoryCache.Set(key, queue);
     }
     else
     {
         _memoryCache.Set(key, SetMemoryValue(model));
     }
 }
Ejemplo n.º 22
0
        public async Task <IActionResult> Index(CalculateModel model)
        {
            //if (!string.IsNullOrEmpty(model.PostalCode) && model.Salary > 0)
            //{
            if (ModelState.IsValid)
            {
                try
                {
                    var taxAmount = await _apiClient.Client.CalculateAsync(Convert.ToDouble(model.Salary), model.PostalCode);

                    model.TaxAmount  = taxAmount;
                    model.Calculated = true;
                }
                catch (ApiException e)
                {
                    model.ErrorMessage = JsonConvert.DeserializeObject <ApiErrorModel>(e.Response).Error;
                }
            }
            //}

            return(View(model));
        }
Ejemplo n.º 23
0
        public ActionResult Sum(CalculateModel modelForCalulte)
        {
            ResultModel resultFromSum = new ResultModel()
            {
                Operator      = "+",
                FirstNumber   = modelForCalulte.FirstNumber,
                SecondNunmber = modelForCalulte.SecondNumber
            };

            decimal temporarySum;

            try
            {
                temporarySum         = modelForCalulte.FirstNumber + modelForCalulte.SecondNumber;
                resultFromSum.Result = temporarySum;
                return(View(resultFromSum));
            }
            catch (FormatException ex)
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 24
0
        public ActionResult Index(CalculateModel model)
        {
            ViewBag.Operations = GetOperations();
            if (model.SecondNumber == 0 && model.Operation == OperationEnum.Division)
            {
                ModelState.AddModelError(nameof(CalculateModel.Result), "Division by zero");
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var calculatorOperationService = _serviceProvider
                                             .GetServices <ICalculateService>()
                                             .Single(x => x.Operation == model.Operation);

            model.Result = calculatorOperationService.Calculate(model.FirstNumber, model.SecondNumber);
            _calculateCacheService.SetCacheValue(GetClientIPAddress(Request.HttpContext), model);

            return(View(model));
        }
Ejemplo n.º 25
0
        public static async Task <CalculateModel> Calculate(decimal income, decimal expenses, DateTime untilDate)
        {
            try
            {
                CalculateModel response = new CalculateModel
                {
                    Income      = income,
                    Expenses    = expenses,
                    UntilDate   = untilDate,
                    DaysInMonth = DateTime.DaysInMonth(untilDate.Year, untilDate.Month)
                };

                Console.WriteLine($"Response: {JsonConvert.SerializeObject(response)}");

                return(await Task.FromResult(response));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 26
0
 private string SetMemoryValue(CalculateModel model)
 {
     return(string.Concat(model.FirstNumber, model.Operation.GetDescription(), model.SecondNumber, "=", model.Result));
 }
Ejemplo n.º 27
0
        public CalculateViewModel DisplayPage(CalculateViewModel viewModel)
        {
            var model = new CalculateModel(viewModel, _deliveryCostCalculator, _config);

            return(model.ViewModel);
        }
Ejemplo n.º 28
0
 public IActionResult Insert(CalculateModel Model)
 {
     try {
         using (TransactionScope ts = new TransactionScope()) {
             var connStr = "Server=db_cont;Port=5432;User ID=postgres;Database=sample;Password=postgres;Enlist=true";
             using (NpgsqlConnection conn = new NpgsqlConnection(connStr)) {
                 conn.Open();
                 var sql = $@"
                     INSERT INTO project_mst (
                         company_id, 
                         project_name, 
                         create_staff_id, 
                         create_program, 
                         create_timestamp, 
                         update_staff_id, 
                         update_program, 
                         update_timestamp
                     ) VALUES (
                         :companyid,
                         :projectname,
                         :createstaffid,
                         :createprogram,
                         :createtimestamp,
                         :updatestaffid,
                         :updateprogram,
                         :updatetimestamp
                     );
                 ";
                 var cmd = new NpgsqlCommand(sql, conn);
                 cmd.Parameters.Add(new NpgsqlParameter("companyid", DbType.String)
                 {
                     Value = "cid"
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("projectname", DbType.String)
                 {
                     Value = "projectname"
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("createstaffid", DbType.Int32)
                 {
                     Value = 1
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("createprogram", DbType.String)
                 {
                     Value = "sampleins"
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("createtimestamp", DbType.DateTime)
                 {
                     Value = DateTime.Now
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("updatestaffid", DbType.Int32)
                 {
                     Value = 1
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("updateprogram", DbType.String)
                 {
                     Value = "sampleupd"
                 });
                 cmd.Parameters.Add(new NpgsqlParameter("updatetimestamp", DbType.DateTime)
                 {
                     Value = DateTime.Now
                 });
                 cmd.ExecuteNonQuery();
             }
             ts.Complete();
         }
         return(Json("success"));
     } catch (Exception ex) {
         _logger.Debug(ex.Message);
         _logger.Debug(ex.StackTrace);
         throw ex;
     }
 }