public BResult <CalculatePostfixResponse> MathOperator(string leftOperand, string rightOperand) { var result = new BResult <CalculatePostfixResponse>() { Result = new CalculatePostfixResponse() }; if (!int.TryParse(leftOperand, out int lOperand)) { result.Error.Add(new HError("ModulusOperator", $"leftOperand ({leftOperand}) is not an integer")); } if (!int.TryParse(rightOperand, out int rOperand)) { result.Error.Add(new HError("ModulusOperator", $"rightOperand ({rightOperand}) is not an integer")); } if (rOperand == 0) { result.Error.Add(new HError("ModulusOperator", $"cannot divide by 0 - leftOperand: {leftOperand}, rightOperand: {rightOperand}")); } if (result.Error.Count == 0) { result.Result.CalculatedValue = lOperand % rOperand; } return(result); }
public async void TestProcessor_BadInput(string infix, int value) { var request = new CalculatorRequest() { Input = infix }; BResult <CalculatorResponse> result = await new CalculateProcessor().ExecuteAsync(request); Assert.Equal(value, result.Result.Output); Assert.NotEmpty(result.Error); }
public int Login(LoginModel loginModel, out Lib.BResult result) { result = new BResult(); var user = _userProfileRepo.Get().Where(x => x.UserName.Equals(loginModel.UserName, StringComparison.CurrentCultureIgnoreCase)); if (user == null || user.Count() != 1) { result.AddError("error", "not found"); return(-1); } else { return(user.First().Id); } }
/// <summary> /// Calculate output of postfix expression /// </summary> /// <param name="inputValue"></param> /// <returns></returns> public BResult <CalculatePostfixResponse> Calculate(CalculatePostfixRequest inputValue) { var result = new BResult <CalculatePostfixResponse>() { Result = new CalculatePostfixResponse() }; var stack = new Stack <string>(); IDictionary <string, Operator> operators = inputValue.Operators; IDictionary <string, Type> mathOperators = GetMathOperators(operators); foreach (string token in inputValue.CalculateStack) { var tType = TokenHelper.GetTokenType(token, operators); switch (tType) { case TokenType.NUMBER: stack.Push(token); break; case TokenType.OPERATOR: string rightOperand = stack.Pop(); string leftOperand = stack.Pop(); Type operatorType = mathOperators.Where(k => k.Key.Equals(token)).Select(v => v.Value).FirstOrDefault(); // Check for null operatorType var obj = Activator.CreateInstance(operatorType) as IMathOperator <CalculatePostfixResponse>; BResult <CalculatePostfixResponse> br = obj.MathOperator(leftOperand, rightOperand); result.Error.AddRange(br.Error); stack.Push(br.Result.CalculatedValue.ToString()); break; case TokenType.UNDEFINED: case TokenType.LEFTPARENTHESIS: case TokenType.RIGHTPARENTHESIS: case TokenType.EQUAL: case TokenType.WHITESPACE: default: result.Error.Add(new HError("Calculate", $"Unknown TokenType: {tType}")); break; } } result.Result.CalculatedValue = Convert.ToInt32(stack.Pop()); return(result); }
/// <summary> /// Assumes a HttpMethod.Post only interface /// </summary> /// <returns>http response</returns> public async Task <BResult <WebRequestResponse> > Request(WebRequestRequest <T> wrr) { if (_client == default(HttpClient)) { _client = new HttpClient(); } BResult <WebRequestResponse> result = new BResult <WebRequestResponse> { Result = new WebRequestResponse() { ID = wrr.ID } }; try { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, wrr.URL); foreach (KeyValuePair <string, string> h in wrr.Header) { httpRequestMessage.Headers.Add(h.Key, h.Value); } httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(wrr.Content), Encoding.UTF8, "application/json"); HttpResponseMessage response = await _client.SendAsync(httpRequestMessage, wrr.CancellationToken); String responseContent = await response.Content.ReadAsStringAsync(); result.Result.Content = responseContent; result.Result.StatusCode = response.StatusCode; result.Result.IsSuccessful = response.IsSuccessStatusCode; if (!response.IsSuccessStatusCode) { result.Result.ReasonPhrase = response.ReasonPhrase; } } catch (Exception ex) { result.Error.Add(new HException("WebRequest", "Exception will executing HttpRequest", ex)); } return(result); }
/// <summary> /// Convert from infix to postfix notation /// </summary> /// <param name="request"></param> /// <returns>stack object for postfix calculator</returns> public BResult <CalculateInfixResponse> InfixToPostfix(CalculateInfixRequest request) { BResult <CalculateInfixResponse> result = new BResult <CalculateInfixResponse>() { Result = new CalculateInfixResponse() }; if (request == null || string.IsNullOrWhiteSpace(request.Input) || request.Operators == null || request.Operators.Count == 0) { result.Error.Add(new HError("InfixToPostfix", "Invalid request")); return(result); } var rpnResult = new ShuntingYard().CreateReversePolishNotation(request.Input, request.Operators); result.Error.AddRange(rpnResult.Error); result.Result.CalculateStack = rpnResult.Result; return(result); }
public UserProfileModel GetById(int id, out Lib.BResult result) { result = new BResult(); var userDal = _userProfileRepo.Find(id); if (userDal == null) { result.AddError("error", "not found in db"); return(null); } var user = new UserProfileModel(userDal); if (user == null) { result.AddError("error", "error converting to bll"); return(null); } else { return(user); } }
public BResult <CalculatePostfixResponse> MathOperator(string leftOperand, string rightOperand) { var result = new BResult <CalculatePostfixResponse>() { Result = new CalculatePostfixResponse() }; if (!int.TryParse(leftOperand, out int lOperand)) { result.Error.Add(new HError("SubtractOperator", $"operand1 ({leftOperand}) is not an integer")); } if (!int.TryParse(rightOperand, out int rOperand)) { result.Error.Add(new HError("SubtractOperator", $"operand2 ({rightOperand}) is not an integer")); } if (result.Error.Count == 0) { result.Result.CalculatedValue = lOperand - rOperand; } return(result); }
public BResult <CalculatePostfixResponse> MathOperator(string leftOperand, string rightOperand) { var result = new BResult <CalculatePostfixResponse>() { Result = new CalculatePostfixResponse() }; if (!int.TryParse(leftOperand, out int lOperand)) { result.Error.Add(new HError("PowerOperator", $"leftOperand ({leftOperand}) is not an integer")); } if (!int.TryParse(rightOperand, out int rOperand)) { result.Error.Add(new HError("PowerOperator", $"rightOperand ({rightOperand}) is not an integer")); } if (result.Error.Count == 0) { result.Result.CalculatedValue = Convert.ToInt32(Math.Pow(lOperand, rOperand)); } return(result); }
public BResult <List <string> > CreateReversePolishNotation(string infix, IDictionary <string, Operator> operators) { BResult <List <string> > result = new BResult <List <string> > { Result = default(List <string>) }; List <string> output = new List <string>(); Stack <string> op = new Stack <string>(); for (int i = 0; i < infix.Length; i++) { var ch = infix[i].ToString(); var chType = TokenHelper.GetTokenType(ch, operators); switch (chType) { case TokenType.NUMBER: // Get complete number and push on output stack StringBuilder number = new StringBuilder(ch); while (i < infix.Length - 1) { ch = infix[i + 1].ToString(); if (TokenHelper.GetTokenType(ch, operators) == TokenType.NUMBER) { number.Append(ch); i++; } else { break; } } output.Add(number.ToString()); break; case TokenType.OPERATOR: // Pop op w/ greater precedence then push current operator onto stack while (op.Count > 0 && TokenHelper.GetTokenType(op.Peek(), operators) != TokenType.LEFTPARENTHESIS && CompareOperators(operators, ch, op.Peek())) { output.Add(op.Pop()); } op.Push(ch); break; case TokenType.LEFTPARENTHESIS: // Push left parentheses op.Push(ch); break; case TokenType.RIGHTPARENTHESIS: // Pop operators and push onto output until left parentheses is reached while (op.Count > 0 && TokenHelper.GetTokenType(op.Peek(), operators) != TokenType.LEFTPARENTHESIS) { output.Add(op.Pop()); } if (op.Count == 0) { result.Error.Add(new HError("ShuntingYard", "Mismatched parentheses")); } op.Pop(); break; case TokenType.WHITESPACE: // Skip case TokenType.EQUAL: break; case TokenType.UNDEFINED: // Indicate bad char default: result.Error.Add(new HError("ShuntingYard", $"Unknown TokenType: {chType}")); break; } } while (op.Count > 0) // Pop remaining operators onto output stack { if (TokenHelper.GetTokenType(op.Peek(), operators) == TokenType.LEFTPARENTHESIS) { result.Error.Add(new HError("ShuntingYard", "Mismatched parentheses")); } output.Add(op.Pop()); } result.Result = output; return(result); }
public async Task <BResult <CalculatorResponse> > ExecuteAsync(CalculatorRequest request) { BResult <CalculatorResponse> result = new BResult <CalculatorResponse> { Result = new CalculatorResponse() }; try { if (string.IsNullOrWhiteSpace(request.Input)) { result.Error.Add(new HError("Calculator", "Invalid request - null input")); } if (request.Input.Any(c => char.IsLetter(c))) { result.Error.Add(new HError("Calculator", "Invalid input - contains letters")); } if (!request.Input.EndsWith("=")) { result.Error.Add(new HError("Calculator", "Invalid input - Expression must end with '='")); } if (_operators == null || _operators.Count == 0) { result.Error.Add(new HError("Calculator", "Invalid operator creation")); return(result); } // Check input string against valid list of valid operators / digits List <char> goodChar = _operators.Keys.SelectMany(s => s.ToCharArray()).ToList(); goodChar.AddRange(new List <char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '=', '(', ')' }); if (request.Input.Except(goodChar).Any()) { string validChar = string.Join(", ", goodChar.Select(c => c.ToString()).ToArray()); result.Error.Add(new HError("Calculator", $"Invalid input - Valid inputs are: {validChar}")); } if (result.Error.Count > 0) { return(result); } var calculateInputRequest = new CalculateInfixRequest() { Input = request.Input, Operators = _operators }; BResult <CalculateInfixResponse> bResultInput = new InfixToPostfixProcessor().InfixToPostfix(calculateInputRequest); result.Error.AddRange(bResultInput.Error); //if (result.Error.Any()) // return result; var calulateOutputRequest = new CalculatePostfixRequest() { CalculateStack = bResultInput.Result.CalculateStack, Operators = _operators }; BResult <CalculatePostfixResponse> bResultOutput = new CalculatePostfixProcessor().Calculate(calulateOutputRequest); result.Error.AddRange(bResultOutput.Error); result.Result.Output = bResultOutput.Result.CalculatedValue; } catch (Exception ex) { result.Error.Add(new HException(_herrorRepository, "Calculator", "Exception will executing Calculator", ex)); } await Task.Delay(0); return(result); }
public async Task <IHttpActionResult> Post([FromBody] CalculatorRequest request) { BResult <CalculatorResponse> result = await new CalculateProcessor().ExecuteAsync(request); return(ResponseMessage(new ActionResponse <CalculatorResponse>().CreateResponse(result))); }