private void Exp_EvaluateFunction(string name, NCalc.FunctionArgs args) { var p = args.EvaluateParameters(); args.HasResult = false; switch (name) { case "_": if (p.Length > 0) { args.HasResult = true; if (_isStateDependent && _internalState != null) { args.Result = GetValueByPath(_internalState, p[0].ToString()); } else { args.Result = Dispatcher.Invoke <object>(() => GetValueByPath(State, p[0].ToString())); } } break; //string functions case "split": if (p.Length > 1 && p[0] is string && p[1] is string) { args.HasResult = true; args.Result = ((string)p[0]).Split(new string[] { (string)p[1] }, StringSplitOptions.RemoveEmptyEntries); } break; case "trim": if (p.Length > 0 && p[0] is string) { args.HasResult = true; args.Result = ((string)p[0]).Trim(); } break; //vMix functions case "API": //state.SendFunction(string.Format(cmd.Action.FormatString, cmd.InputKey, CalculateExpression<int>(cmd.Parameter), Dispatcher.Invoke(() => CalculateObjectParameter(cmd)), CalculateExpression<int>(cmd.Parameter) - 1, input.HasValue ? input.Value : 0), false); break; //array functions case "getvalue": if (p.Length > 1 && p[0] is Array && p[1] is int) { args.HasResult = true; args.Result = ((Array)p[0]).GetValue((int)p[1]); } break; } }
private void EvaluateFunction(string name, NCalc.FunctionArgs args) { if (String.Equals(name, FunctionIsNull, StringComparison.OrdinalIgnoreCase)) { args.HasResult = true; args.Result = args.EvaluateParameters().Any(x => x == null); } else if (String.Equals(name, FunctionCount, StringComparison.OrdinalIgnoreCase)) { args.HasResult = true; args.Result = AggregationFunctions.Count(_descriptor.Value, _dataset.Culture, AggregationFunctions.Unpack(args.EvaluateParameters())); } else if (String.Equals(name, FunctionAverage, StringComparison.OrdinalIgnoreCase)) { args.HasResult = true; args.Result = AggregationFunctions.Average(_descriptor.Value, _dataset.Culture, AggregationFunctions.Unpack(args.EvaluateParameters())); } else if (String.Equals(name, FunctionLet, StringComparison.OrdinalIgnoreCase)) { if (args.Parameters.Length != 2) { throw new ArgumentException($"Invalid number of arguments for {FunctionLet}()."); } var result = args.Parameters[1].Evaluate(); _currentExpression.Parameters.Add(Convert.ToString(args.Parameters[0].Evaluate()), result); args.HasResult = true; args.Result = result; } else if (String.Equals(name, FunctionLastOf, StringComparison.OrdinalIgnoreCase)) { args.HasResult = true; args.Result = args.EvaluateParameters().LastOrDefault(); } else if (String.Equals(name, FunctionSum, StringComparison.OrdinalIgnoreCase)) { if (args.Parameters.Length == 0 || args.Parameters.Length > 2) { throw new ArgumentException($"Invalid number of arguments for {FunctionSum}()."); } var set = (IEnumerable <object>)args.Parameters[0].Evaluate(); if (args.Parameters.Length == 2) { set = AggregationFunctions.Project(_descriptor.Value, _dataset.Culture, set, args.Parameters[1]); } args.HasResult = true; args.Result = AggregationFunctions.Sum(_descriptor.Value, _dataset.Culture, set); } }
public void SetFunctionTest_FunctionWithTextParameter_Success() { var parameters = new NCalc.Expression[2]; parameters[0] = new NCalc.Expression("'a'"); parameters[1] = new NCalc.Expression("'par'"); var functionArgs = new NCalc.FunctionArgs() { Parameters = parameters }; Assert.That(_setFunction.Function(functionArgs), Is.EqualTo(true)); Assert.That(functionArgs.Parameters[0].Parameters.ContainsKey("a")); Assert.That(functionArgs.Parameters[0].Parameters["a"], Is.EqualTo("par")); }
public void SetFunctionTest_FunctionWithManyParameters_Success() { var parameters = new NCalc.Expression[4]; parameters[0] = new NCalc.Expression("'a'"); parameters[1] = new NCalc.Expression("8"); parameters[2] = new NCalc.Expression("'b'"); parameters[3] = new NCalc.Expression("1"); var functionArgs = new NCalc.FunctionArgs() { Parameters = parameters }; Assert.That(_setFunction.Function(functionArgs), Is.EqualTo(true)); Assert.That(functionArgs.Parameters[0].Parameters.ContainsKey("a")); Assert.That(functionArgs.Parameters[0].Parameters["a"], Is.EqualTo(8)); Assert.That(functionArgs.Parameters[0].Parameters.ContainsKey("b")); Assert.That(functionArgs.Parameters[0].Parameters["b"], Is.EqualTo(1)); }
public void CalculateFunctionTest_ScriptFromFakeAssembly_Success() { var parameters = new NCalc.Expression[5]; parameters[0] = new NCalc.Expression("'a'"); parameters[1] = new NCalc.Expression("'par1'"); parameters[2] = new NCalc.Expression("1"); parameters[3] = new NCalc.Expression("'par2'"); parameters[4] = new NCalc.Expression("3"); var result = new Mock <IResult>(); result.Setup(r => r.Properties) .Returns(new Dictionary <string, object>() { { "result", "4" } }); var calculator = new Mock <ICalculator>(); calculator.Setup(c => c.Map(It.IsAny <IList <object> >())); calculator.Setup(c => c.Calculate()).Returns(result.Object); var calculateFunction = new CalculateFunction(calculator: calculator.Object); var functionArgs = new NCalc.FunctionArgs() { Parameters = parameters }; Assert.That((bool)calculateFunction.Function(functionArgs), Is.EqualTo(true)); calculator.Verify(c => c.Map(It.IsAny <IList <object> >()), Times.Once); calculator.Verify(c => c.Calculate(), Times.Once); Assert.That(functionArgs.Parameters[0].Parameters.ContainsKey("#result")); Assert.That(functionArgs.Parameters[0].Parameters["#result"], Is.EqualTo("4")); }
public void CalculateFunctionTest_ScriptFromFakeDatabase_Success() { var scriptRepository = new Mock <IScriptRepository>(); scriptRepository.Setup(sr => sr.GetScriptBaseOnNameAsync("a")) .Returns(Task.FromResult(new Script() { Id = 1, Name = "a", Description = string.Empty })); var parameterRepository = new Mock <IParameterRepository>(); parameterRepository.Setup(pr => pr.GetAllParametersForScriptAsync(1)) .Returns(Task.FromResult(GetParameters())); var calculateFunction = new CalculateFunction(scriptRepository.Object, parameterRepository.Object); var parameters = new NCalc.Expression[5]; parameters[0] = new NCalc.Expression("'a'"); parameters[1] = new NCalc.Expression("'par1'"); parameters[2] = new NCalc.Expression("1"); parameters[3] = new NCalc.Expression("'par2'"); parameters[4] = new NCalc.Expression("3"); var functionArgs = new NCalc.FunctionArgs() { Parameters = parameters }; Assert.That(calculateFunction.Function(functionArgs), Is.EqualTo(true)); Assert.That(functionArgs.Parameters[0].Parameters.ContainsKey("#result")); Assert.That(functionArgs.Parameters[0].Parameters["#result"], Is.EqualTo("4")); }
void server_ProcessRequest(HttpListenerContext context) { /*context.Response.AddHeader("Content-Type", "application/x-force-download"); * context.Response.ContentLength64 = data.Length;*/ context.Response.StatusCode = 200; Interpreter.Interpreter.HandleWrite = (string msg) => { writeStrToContext(context, msg); }; Interpreter.Interpreter.HandleNonEvaluatedLine = (string line) => { Interpreter.Interpreter.HandleWrite(line); }; Interpreter.Interpreter.HandleException = (AzLang.Exception exception) => { //context.Response.OutputStream..writeFailure(); string msg = "[EXCEPTION] " + exception.File + ":" + exception.Line + "\n Message: " + exception.Message + "\n Detail: " + exception.Detail + "\n Suggestions: " + exception.Suggestions + "\n"; Console.WriteLine(msg); writeStrToContext(context, msg); context.Response.OutputStream.Close(); //Reload(); }; Interpreter.Interpreter.NonStockMethods["flush"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { if (context.Response.OutputStream.CanWrite) { context.Response.OutputStream.Flush(); } }; Interpreter.Interpreter.NonStockMethods["status_code"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(int))) { int code = (int)param; context.Response.StatusCode = code; } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'Int32', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(AzLang.Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }; Interpreter.Interpreter.NonStockMethods["web_get_client_ip"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; try { args.Result = ((IPEndPoint)context.Request.RemoteEndPoint).Address.ToString(); } catch { } }; Interpreter.Interpreter.NonStockMethods["web_get_client_port"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; try { args.Result = ((IPEndPoint)context.Request.RemoteEndPoint).Port.ToString(); } catch { } }; Interpreter.Interpreter.NonStockMethods["get"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string get_var = (string)param; if (context.Request.QueryString.AllKeys.Contains(get_var)) { args.Result = context.Request.QueryString[get_var]; } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Undefined array key.", "The specified GET variable is non-existent.", "")); } } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(AzLang.Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }; Interpreter.Interpreter.NonStockMethods["cookies_contains"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string cookie_name = (string)param; args.Result = context.Request.Cookies[cookie_name] != null; } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(AzLang.Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }; Interpreter.Interpreter.NonStockMethods["cookies"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string cookie_name = (string)param; if (context.Request.Cookies[cookie_name] != null) { args.Result = context.Request.Cookies[cookie_name].Value; } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Undefined array key.", "The specified Cookie name is non-existent.", "")); } } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(AzLang.Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }; Interpreter.Interpreter.NonStockMethods["header"] = (LanguageInterpreter sender, NCalc.FunctionArgs args) => { args.HasResult = true; if (EUtils.CheckArgs(2, args)) { object param = args.EvaluateParameters()[0]; object param2 = args.EvaluateParameters()[1]; if (EUtils.CheckArgType(param, typeof(string))) { if (EUtils.CheckArgType(param2, typeof(string))) { string header = (string)param; string value = (string)param2; context.Response.Headers.Add(header, value); } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(AzLang.Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }; if (context.Request.Url.AbsolutePath.StartsWith("/_azlang_res/")) { context.Response.Headers["Cache-Control"] = "max-age=120"; string req_icon = context.Request.Url.AbsolutePath.Remove(0, 13); req_icon = req_icon.Split('.')[0]; if (File.Exists("Resources/" + req_icon + ".png")) { byte[] image = imageToByteArray((Image)ResourceIcon(req_icon)); context.Response.OutputStream.Write(image, 0, image.Length); } else { Handle404(context, context.Request.Url.AbsolutePath); } } else { Dictionary <string, RequestHandler> matches = RequestHandlers.Where(val => val.Key == context.Request.Url.AbsolutePath && val.Value.Method.ToString().ToLower() == context.Request.HttpMethod.ToLower()).ToDictionary(val => val.Key, val => val.Value); if (matches.Count > 0) { RequestHandler match = matches.First().Value; if (match.Type == HandlerType.UserFunction) { NCalc.FunctionArgs handler_args = new NCalc.FunctionArgs(); handler_args.Parameters = new NCalc.Expression[1]; handler_args.Parameters[0] = new NCalc.Expression(new RequestContext(context)); Interpreter.ExecuteUserFunction(match.HandlerFunction, handler_args); } else if (match.Type == HandlerType.File) { if (File.Exists(match.FilePath)) { byte[] bytes = File.ReadAllBytes(match.FilePath); context.Response.OutputStream.Write(bytes, 0, bytes.Length); //writeStrToContext(context, File.ReadAllText(match.FilePath)); } else { Handle404(context, match.FilePath); //Interpreter.Interpreter.HandleException(new AzLang.Exception(Interpreter.Interpreter.CurrentFile, Interpreter.Interpreter.CurrentLine, "File '" + match.FilePath + "' is non-existent", "", "")); } } Console.WriteLine(((IPEndPoint)context.Request.RemoteEndPoint).Address.ToString() + ":" + ((IPEndPoint)context.Request.RemoteEndPoint).Port.ToString() + "; request handled: " + match.UriAbsPath + ", method: " + match.Method); } else { Dictionary <string, RequestHandler> dir_matches = RequestHandlers.Where(val => context.Request.Url.AbsolutePath.StartsWith(val.Key) && val.Value.Method.ToString().ToLower() == context.Request.HttpMethod.ToLower() && val.Value.Type == HandlerType.File).ToDictionary(val => val.Key, val => val.Value); if (dir_matches.Count > 0) { RequestHandler dir_match = dir_matches.First().Value; if (Directory.Exists(dir_match.FilePath)) { string relative_path = context.Request.Url.AbsolutePath.Remove(context.Request.Url.AbsolutePath.IndexOf(dir_match.UriAbsPath), dir_match.UriAbsPath.Length); if (File.Exists(dir_match.FilePath + relative_path)) { byte[] bytes = File.ReadAllBytes(dir_match.FilePath + relative_path); context.Response.OutputStream.Write(bytes, 0, bytes.Length); } else { if (Directory.Exists(dir_match.FilePath + relative_path)) { HandleDirectoryListing(context, dir_match.FilePath + relative_path); } else { Handle404(context, dir_match.FilePath + relative_path.Remove(0, 1)); } } } else { Handle404(context, dir_match.FilePath); } } else { context.Response.StatusCode = 503; writeStrToContext(context, "<h1>Request handler not defined.</h1>The request handler for \"<em>" + context.Request.Url.AbsolutePath + "</em>\" via method <b>" + context.Request.HttpMethod + "</b> is non-existent."); } } } //context.Response.OutputStream.Write(data, 0, data.Length); try { if (context.Response.OutputStream.CanWrite) { context.Response.Close(); } } catch { } }