public IEnumerable <CalculationResponse> Execute(CalculationRequest query) { foreach (var item in query.Data) { switch (item.TaxRate) { case TaxRate.Exempt: yield return(MapToResponse(_taxCalculator.VATTax0Rate, item)); break; case TaxRate.Reduced5: yield return(MapToResponse(_taxCalculator.VATTax5Rate, item)); break; case TaxRate.Reduced8: yield return(MapToResponse(_taxCalculator.VATTax8Rate, item)); break; case TaxRate.Standard: yield return(MapToResponse(_taxCalculator.VATTaxBaseRate, item)); break; } } }
public ActionResult <CalculationResponse> Post([FromBody] CalculationRequest value) { try { var recordCount = value.Numbers.Count(); // todo read from settings file. if (recordCount > MaxCollectionSize || recordCount <= 1) { return(ReturnPayloadIncorrect(recordCount)); } var calculation = _calculationFactory.Build(value.CalculationType); var returnedCalculation = _map.From(calculation.Calculate(value.Numbers)); return(Ok(returnedCalculation)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { // todo could use settings to make sure messages are sent based on usage (internal/external/etc.) Content = new StringContent($"An unhandled exception occurred, see log for full details. {ex.Message}") }; return(StatusCode(500, response)); } }
public ActionResult Index(CalculationRequest request, bool isBack = false) { ViewBag.Request = request; if (isBack) { ViewBag.Currencies = uow.CurrencyRepository.GetAll(); ViewBag.Countries = uow.GetCountryHasData(); ViewBag.PatentFeeTypes = uow.PatentTypeRepository.GetAll(); return(View(request)); } if (ModelState.IsValid) { var model = uow.CalculatePatentFees(request); if (model != null) { ViewBag.DropdownSource = ComputeDropdownSource(model); ViewBag.CreateCountry = uow.CountryRepository.GetByID(request.CountryCode).Name; model.ApplicationPatentNo = HttpUtility.HtmlDecode(model.ApplicationPatentNo); return(View("Report", model)); } } AddAlert(AlertType.DANGER, "There is no setup for Offical Fee/Agency Fee. Please go to Admin section to setup!"); SetViewBagData(); return(View(request)); }
public ActionResult <CalculationResponse> CalculateTax([FromBody] CalculationRequest request) { var taxType = _postalCodeToTaxTypeMapper.GetTaxRegime(request.PostalCode); var response = new CalculationResponse(); if (taxType == TaxType.Unknown) { var errorMessage = $"Postal code {request.PostalCode} could not be mapped to a valid tax type."; response.ErrorMessage = errorMessage; _logger.LogWarning(errorMessage); } else { var taxDue = _taxManager.GetCalculator(taxType).GetTaxableAmount(request.TaxableAmount); response.AssessedAmount = taxDue; response.TaxType = taxType; //i wanted to use Automap to handle this mapping but no time for that and this mapping is only //done here anyway _taxEventLogger.LogEvent(new Domain.TaxCalculationEvent() { AssessedAmount = response.AssessedAmount, PostalCode = request.PostalCode, TaxRegime = taxType, TaxableAmount = request.TaxableAmount, UserId = request.UserId }); } return(response); }
public async Task <CalculationRequest> DownloadContentAsync(string downloadUrl) { var content = await httpClient.GetStringAsync(downloadUrl); CalculationRequest requestBody = JsonConvert.DeserializeObject <CalculationRequest>(content); return(requestBody); }
private CalculationData ParseRequest(CalculationRequest request) { return(new CalculationData { Operand1 = decimal.Parse(request.Operand1), Operand2 = decimal.Parse(request.Operand2), MathOperation = (MathOperations)Enum.Parse(typeof(MathOperations), request.MathOperation) }); }
public IActionResult CalcResult([FromBody] CalculationRequest request) { var response = _serv.Evaluate(request); return(Json(new { result = response != null ? response.Result.ToString() : "Invalid expression", })); }
public void RunAllMetrics(CalculationRequest calculationRequest, MapReduceWrapper mapReduceWrapper) { foreach (var metric in _metrics) { var response = metric.Calculate(calculationRequest, mapReduceWrapper); PrintResponse(response); } }
static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory(); // "guest"/"guest" by default, limited to localhost connections factory.HostName = "localhost"; factory.VirtualHost = "/"; factory.Port = 5673; factory.UserName = "******"; factory.Password = "******"; IConnection conn = factory.CreateConnection(); IModel channel = conn.CreateModel(); var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { string requestData = System.Text.Encoding.UTF8.GetString(e.Body); CalculationRequest request = JsonConvert.DeserializeObject <CalculationRequest>(requestData); Console.WriteLine("Request received:" + request.ToString()); CalculationResponse response = new CalculationResponse(); if (request.Operation == OperationType.Add) { response.Result = request.Number1 + request.Number2; } else if (request.Operation == OperationType.Subtract) { response.Result = request.Number1 - request.Number2; } string responseData = JsonConvert.SerializeObject(response); var basicProperties = channel.CreateBasicProperties(); basicProperties.Headers = new Dictionary <string, object>(); basicProperties.Headers.Add(Constants.RequestIdHeaderKey, e.BasicProperties.Headers[Constants.RequestIdHeaderKey]); string responseQueueName = Encoding.UTF8.GetString((byte[])e.BasicProperties.Headers[Constants.ResponseQueueHeaderKey]); channel.BasicPublish( "", responseQueueName, basicProperties, Encoding.UTF8.GetBytes(responseData)); }; channel.BasicConsume("requests", true, consumer); Console.WriteLine("Press a key to exit."); Console.ReadKey(); channel.Close(); conn.Close(); }
public async Task <CalculationResult> CalculateBasket(CalculationRequest calculationRequest) { var response = await _pricingReadService.PostAsync("/api/calculator", new StringContent(JsonConvert.SerializeObject(calculationRequest), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsAsync <CalculationResult>()); }
// GET: Calculator public ActionResult Index() { var model = new CalculationRequest(); SetViewBagData(); model.CountryCode = "ID"; model.CurrencyCode = "IDR"; model.ReportTypeId = ReportType.TotalAnnuities; return(View(model)); }
public void Handle(CalculationRequest request) { var productsOrder = request.NotCalculatedOrders.FirstOrDefault(x => x.Product == Product); if (productsOrder?.Count >= _quantity) { productsOrder.Count = productsOrder.Count - _quantity; request.TotalPrice += _price; } }
private CalculationResponse MassageData(CalculationRequest requestBody) { var response = new CalculationResponse(); var airConditionerParcels = requestBody.Objects.Where(parcel => parcel.Category == AirConditionerCategory); response.ParcelCount = airConditionerParcels.Count(); response.TotalParcelCount = requestBody.Objects.Count(); response.TotalValue = airConditionerParcels.Sum(parcel => CalculateWeight(parcel)); response.Category = AirConditionerCategory; return(response); }
static void Main() { ConnectionFactory factory = new ConnectionFactory { HostName = "localhost", VirtualHost = "/", Port = 5672, UserName = "******", Password = "******" }; IConnection connection = factory.CreateConnection(); IModel channel = connection.CreateModel(); var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, eventArgs) => { var messageData = Encoding.UTF8.GetString(eventArgs.Body.ToArray()); CalculationRequest request = JsonConvert.DeserializeObject <CalculationRequest>(messageData); Console.WriteLine($"Request received: {request}"); CalculationResponse response = new CalculationResponse(); if (request.OperationType == OperationType.Add) { response.Result = request.Number1 + request.Number2; } else { response.Result = request.Number1 - request.Number2; } var responseData = JsonConvert.SerializeObject(response); var basicProperties = channel.CreateBasicProperties(); basicProperties.Headers = new Dictionary <string, object>() { { CommonCode.Constants.RequestIdHeaderKey, eventArgs.BasicProperties.Headers[CommonCode.Constants.RequestIdHeaderKey] } }; channel.BasicPublish("", "response", basicProperties, Encoding.UTF8.GetBytes(responseData)); }; channel.BasicConsume("request", true, consumer); Console.WriteLine("Press a key for exist"); Console.ReadLine(); channel.Close(); connection.Close(); }
public void Calculate(CalculationRequest calculation) { var tariffRate = calculation.Tariff.Rates.First(tr => tr.StartDate.Date == calculation.FromDate.Date); calculation.UsageT1.AddCalculation(new UsageCalculation { Charge = Math.Round(calculation.UsageT1.Units * tariffRate.Value, 2, MidpointRounding.AwayFromZero), PriceValue = tariffRate.Value, Units = calculation.UsageT1.Units, }); }
public ActionResult <List <CalculationResponse> > CalculatePaymentPlan([FromBody] CalculationRequest data) { var response = _loanTypeService.CalculatePaymentPlan(data); if (response == null) { return(BadRequest(new { message = "Can't calculate the values" })); } return(response); }
public JsonResult Index([FromBody] CalculationRequest calculationRequest) { var calculationResponse = new CalculationResponse(); if (calculationRequest.Operation.Equals("add", StringComparison.OrdinalIgnoreCase)) { calculationResponse.CalculationResult = _calculatorService.Add(calculationRequest.Input).ToString(); } return(Json(calculationResponse)); }
public HttpResult Multiply([FromBody] CalculationRequest request) { var result = Calculator.Multiply(request.firstNum, request.secondNum); return(new HttpResult { Data = result, Message = "The multiplication calculation has been completed successfully.", Success = true }); }
public async Task <IActionResult> StartCalculation(CalculationRequest request) { if (!ModelState.IsValid) { return(BadRequest(request)); } var newCalculatorJob = _mapper.Map <CalculatorJob>(request); var guid = await _calculatorService.StartCalculation(newCalculatorJob); return(Ok(guid)); }
public CalculationResponse Calculate([FromBody] CalculationRequest request, [FromQuery] bool colored = false) { var result = calculator.Calculate((Operation)request.Operation, request.Operands); if (colored) { var color = colorProvider.GetColor(result); return(new CalculationColorResponse(result, color)); } return(new CalculationResponse(result)); }
public OperationResult Calculate(CalculationRequest request) { var validationResult = _calculationRequestValidator.Validate(request); if (!validationResult.IsOk) { return(new OperationResult(validationResult.ErrorMessage)); } var calculationData = ParseRequest(request); return(_calculator.Calculate(calculationData)); }
public CalculationResponse Calculate(CalculationRequest calculationRequest, MapReduceWrapper mapReduceWrapper) { var res = mapReduceWrapper.mapReduce.ToList().OrderByDescending(kvp => kvp.Value).First(); var response = new CalculationResponse { MetricName = this.GetType().Name, ResultWord = res.Key, ResultWordCount = res.Value }; return(response); }
public CalculationResponse Calculate(CalculationRequest calculationRequest, MapReduceWrapper mapReduceWrapper) { var resList = mapReduceWrapper.mapReduce.ToList().OrderByDescending(kvp => kvp.Value).Take(10); var response = new CalculationResponse { MetricName = this.GetType().Name, ResultWords = resList.Select(kvp => kvp.Key).ToList(), ResultWordsCount = resList.Select(kvp => kvp.Value).ToList() }; return(response); }
public double GetCalculation(CalculationRequest request) { _logger.LogInformation("Processing a calculation request."); return(request.Type switch { CalculationType.Add => _calculator.Add(request.Start, request.Amount), CalculationType.Subtract => _calculator.Subtract(request.Start, request.Amount), CalculationType.Multiply => _calculator.Multiply(request.Start, request.By), CalculationType.Divide => _calculator.Divide(request.Start, request.By), CalculationType.Prime => _calculator.GetPrimeNumber(request.Index), _ => 0, });
public async Task <CalculationResult> Post([FromBody] CalculationRequest calculationRequest) { var equipments = await _equipmentService.GetEquipments(); var prices = _pricingRepository.GetMultiple(new List <int> { 1, 2, 3, 4, 5, 6, 7 }); var loyalties = _loyaltyRepository.GetMultiple(new List <int> { 1, 2, 3 }); var fees = _feeRepository.GetMultiple(new List <int> { 1, 2, 3 }); //todo : needs to be unit tested! var result = new CalculationResult(); int loyaltyPoints = 0; foreach (var requestLineItem in calculationRequest.LineItems) { int lineItemCost = 0; var equipmentType = equipments.First(x => x.Name == requestLineItem.EquipmentName).EquipmentType; prices.Where(x => x.EquipmentType == equipmentType).ToList().ForEach(x => { if (x.StartingDay == 0 && x.EndingDay == 0) { lineItemCost += fees.Where(y => y.Tag == x.FeeTag).Sum(z => z.Cost); } if (x.StartingDay <= requestLineItem.RentalDays && requestLineItem.RentalDays <= x.EndingDay) { lineItemCost += fees.Where(y => y.Tag == x.FeeTag).Sum(z => z.Cost); } }); loyaltyPoints += loyalties.Where(x => x.EquipmentType == equipmentType).Sum(x => x.Points); result.GenerateInvoiceLineItemResults.Add(new LineItemCalculationResult { Name = requestLineItem.EquipmentName, Cost = lineItemCost }); } result.LoyaltyPoints = loyaltyPoints; result.TotalPrice = result.GenerateInvoiceLineItemResults.Sum(x => x.Cost); return(result); }
public CalculationResponse Calculate(CalculationRequest request) { if (request.Request == RequestType.Add) { return(new CalculationResponse(request.Number1 + request.Number2)); } else if (request.Request == RequestType.Substract) { return(new CalculationResponse(request.Number1 - request.Number2)); } return(new CalculationResponse(0)); }
public static void Main(string[] args) { string fileName = null; if (args.Length == 0) { Console.WriteLine("Please provide file name as first parameter"); Console.ReadKey(); return; } fileName = args[0]; if (!File.Exists(fileName)) { Console.WriteLine($"File {fileName} doesn't exist"); Console.ReadKey(); return; } var calculationRequest = new CalculationRequest { BufferSize = 10 * 1024 * 1024, IgnoreArticels = true, StringComparer = StringComparer.CurrentCultureIgnoreCase, SourceFileName = fileName }; var metrics = new List <IMetricCalculator>() { new MostPopularLetter(), new MostPopularWord(), new TenMostPopularWords(), new FindSpecificWords() { Words = new[] { "computer", "football", "weather", "hockey" } } }; var fileProcessor = new FileProcessor() { CalculationRequest = calculationRequest, Metrics = metrics }; fileProcessor.Process(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); }
private static void sendRequest(ConcurrentDictionary <string, CalculationRequest> waitingRequest , IModel channel, CalculationRequest request) { string requestId = Guid.NewGuid().ToString(); string requestData = JsonConvert.SerializeObject(request); waitingRequest[requestId] = request; var basicProperties = channel.CreateBasicProperties(); basicProperties.Headers = new Dictionary <string, object>(); basicProperties.Headers.Add(Constants.RequestIdHeaderKey, Encoding.UTF8.GetBytes(requestId)); channel.BasicPublish("", "requests", basicProperties, Encoding.UTF8.GetBytes(requestData)); }
public void Send(CalculationRequest vrequest) { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = IPAddress.Parse(vrequest.URL); IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8080); // Create a TCP/IP socket. Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { sender.Connect(remoteEP); Console.WriteLine($"Socket connected to {sender.RemoteEndPoint}"); string requestString = Newtonsoft.Json.JsonConvert.SerializeObject(vrequest); byte[] msg = Encoding.ASCII.GetBytes($"{requestString}<EOF>"); //send the data through the socket int bytesSent = sender.Send(msg); //receive the response from the remote device. int bytesRec = sender.Receive(bytes); VResponse = Encoding.ASCII.GetString(bytes, 0, bytesRec); sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException argsNullEx) { Console.WriteLine($"Argument null exception {argsNullEx}"); } catch (SocketException socketException) { Console.WriteLine($"SocketException : {socketException}"); } catch (Exception ex) { Console.WriteLine($"Unexpected exception caught {ex}"); } } catch (Exception e) { Console.WriteLine($"Unexpected (outer) exception caught {e}"); } }
public void Calculate_WhenRequestValid_CalledCalculatorService() { var request = new CalculationRequest { Operand1 = "123", Operand2 = "456", MathOperation = "Divide" }; var result = _controller.Calculate(request); _calculatorMock.Verify(x => x.Calculate(It.Is <CalculationData>( z => z.Operand1 == 123 && z.Operand2 == 456 && z.MathOperation == MathOperations.Divide )), Times.Once); }