// Called when a client requests a symbol from the extension domain. private ErrorValue OnRequest(object sender, TcHmiSrvRequestListener.OnRequestEventArgs e) { ErrorValue ret = ErrorValue.HMI_SUCCESS; Context context = e.Context; CommandGroup commands = e.Commands; try { commands.Result = ExtensionErrorValue.HMI_EXT_SUCCESS; string mapping = ""; foreach (Command command in commands) { mapping = command.Mapping; try { // Use the mapping to check which command is requested switch (mapping) { case "LogParameterChangeEvent": ret = LogParameterChangeEvent(context, command); break; case "LogEvent": ret = LogEvent(context, command); break; default: ret = ErrorValue.HMI_E_EXTENSION; break; } } catch (Exception ex) { command.ExtensionResult = ExtensionErrorValue.HMI_EXT_FAIL; command.ResultString = _logger.Localize(context, "ERROR_CALL_COMMAND", new string[] { mapping, ex.Message }); } } } catch { commands.Result = ExtensionErrorValue.HMI_EXT_FAIL; } finally { if (commands.Result != ExtensionErrorValue.HMI_EXT_SUCCESS) { // Reset the read value of the commands to prevent the server from sending invalid data foreach (Command command in commands) { command.ReadValue = null; } ret = ErrorValue.HMI_E_EXTENSION; } } return(ret); }
/// <summary> /// Equals. /// </summary> public override bool Equals(object obj) { if (HasValue) { if (obj is TReturn returnResult) { return(Value.Equals(returnResult)); } if (obj is Result <TReturn, TError> result) { if (result.HasValue) { return(Value.Equals(result.Value)); } } } else { if (obj is Result <TReturn, TError> result) { if (!result.HasValue) { return(ErrorValue.Equals(result.ErrorValue)); } } } return(false); }
// https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-left-mid-right public static FormulaValue Mid(IRContext irContext, FormulaValue[] args) { var errors = new List <ErrorValue>(); NumberValue start = (NumberValue)args[1]; if (double.IsNaN(start.Value) || double.IsInfinity(start.Value) || start.Value <= 0) { errors.Add(CommonErrors.ArgumentOutOfRange(start.IRContext)); } NumberValue count = (NumberValue)args[2]; if (double.IsNaN(count.Value) || double.IsInfinity(count.Value) || count.Value < 0) { errors.Add(CommonErrors.ArgumentOutOfRange(count.IRContext)); } if (errors.Count != 0) { return(ErrorValue.Combine(irContext, errors)); } StringValue source = (StringValue)args[0]; var start0Based = (int)(start.Value - 1); if (source.Value == "" || start0Based >= source.Value.Length) { return(new StringValue(irContext, "")); } var minCount = Math.Min((int)count.Value, source.Value.Length - start0Based); var result = source.Value.Substring(start0Based, minCount); return(new StringValue(irContext, result)); }
/// <summary> /// Check whether this CRM response represents a CRM error, and if it does /// throw it as an exception. /// </summary> /// <param name="jsonResponse">A response from CRM.</param> /// <param name="payload">The payload of the request which gave rise to this response.</param> /// <exception cref="CrmServerErrorException">if the response was recognised as an error.</exception> private void CheckForCrmError(string jsonResponse, string payload) { ErrorValue error; try { error = DeserializeJson <ErrorValue>(jsonResponse); } catch (JsonSerializationException) { // it wasn't recognisable as an error. That's fine! error = new ErrorValue(); } if (error != null && error.IsPopulated()) { switch (Int32.Parse(error.number)) { case 10: case 1008: case 1009: throw new BadCredentialsException(error); default: throw new CrmServerErrorException(error, HttpUtility.UrlDecode(payload)); } } }
public MonitorState GetCurrentState() { string outputFormat = "F2"; float value = 0; value = GetNextValue(); CurrentAgentValue = value; if (value > 9999) { outputFormat = "F0"; } else if (value > 99) { outputFormat = "F1"; } MonitorState currentState = new MonitorState() { ForAgent = Description, CurrentValue = value.ToString(outputFormat), State = GetState(value), CurrentValueUnit = OutputValueUnit }; if (currentState.State == CollectorState.Error) { currentState.RawDetails = string.Format("(Trigger {0})", ErrorValue.ToString(outputFormat)); } else if (currentState.State == CollectorState.Warning) { currentState.RawDetails = string.Format("(Trigger {0})", WarningValue.ToString(outputFormat)); } return(currentState); }
private void UpdateMeasure(ErrorValue time_error) { this.elapsed_time_ref = time_error.ElapsedTime; this.absolute_error = time_error.Absolute; this.relative_error = time_error.Relative; this.absolute_delta_error = time_error.AbsoluteOnDelta; this.relative_delta_error = time_error.RelativeOnDelta; }
public HttpResponseException(object errorObject = null, HttpStatusCode status = HttpStatusCode.InternalServerError) { Status = status; Value = new ErrorValue { Status = (int)status, Errors = errorObject }; }
// Helper to eval an arg that might be a lambda. internal DValue <T> EvalArg <T>(FormulaValue arg, SymbolContext context, IRContext irContext) where T : ValidFormulaValue { if (arg is LambdaFormulaValue lambda) { var val = lambda.Eval(this, context); return(val switch { T t => DValue <T> .Of(t), BlankValue b => DValue <T> .Of(b), ErrorValue e => DValue <T> .Of(e), _ => DValue <T> .Of(CommonErrors.RuntimeTypeMismatch(irContext)) });
public override void Compile() { if (index >= 0) { ilg.Emit(OpCodes.Ldc_I4, index); ilg.Emit(OpCodes.Call, getArrayViewMethod); } else { LoadErrorValue(ErrorValue.Make("#FUNERR: Range on function sheet")); } }
public static FormulaValue SortTable(EvalVisitor runner, SymbolContext symbolContext, IRContext irContext, FormulaValue[] args) { var arg0 = (TableValue)args[0]; var arg1 = (LambdaFormulaValue)args[1]; var arg2 = (StringValue)args[2]; var pairs = arg0.Rows.Select(row => { if (row.IsValue) { var childContext = symbolContext.WithScopeValues(row.Value); return(new KeyValuePair <DValue <RecordValue>, FormulaValue>(row, arg1.Eval(runner, childContext))); } return(new KeyValuePair <DValue <RecordValue>, FormulaValue>(row, row.ToFormulaValue())); }).ToList(); var errors = new List <ErrorValue>(pairs.Select(pair => pair.Value).OfType <ErrorValue>()); var allNumbers = pairs.All(pair => IsValueTypeErrorOrBlank <NumberValue>(pair.Value)); var allStrings = pairs.All(pair => IsValueTypeErrorOrBlank <StringValue>(pair.Value)); var allBooleans = pairs.All(pair => IsValueTypeErrorOrBlank <BooleanValue>(pair.Value)); if (!(allNumbers || allStrings || allBooleans)) { errors.Add(CommonErrors.RuntimeTypeMismatch(irContext)); return(ErrorValue.Combine(irContext, errors)); } if (errors.Count != 0) { return(ErrorValue.Combine(irContext, errors)); } var compareToResultModifier = 1; if (arg2.Value.ToLower() == "descending") { compareToResultModifier = -1; } if (allNumbers) { return(SortValueType <NumberValue, double>(pairs, irContext, compareToResultModifier)); } else if (allStrings) { return(SortValueType <StringValue, string>(pairs, irContext, compareToResultModifier)); } else { return(SortValueType <BooleanValue, bool>(pairs, irContext, compareToResultModifier)); } }
private bool CheckSEH() { var ruleInstance = _currentError.RuleInstance; #if DEBUG //Log($"ruleInstance = {ruleInstance}"); #endif var searchOptions = new LogicalSearchOptions(); searchOptions.TargetStorage = ruleInstance; searchOptions.LocalCodeExecutionContext = _currentCodeFrame.LocalContext; foreach (var sehItem in _currentCodeFrame.CurrentSEHGroup.Items) { #if DEBUG //Log($"sehItem = {sehItem}"); #endif if (sehItem.Condition != null) { searchOptions.QueryExpression = sehItem.Condition; if (!_logicalSearchResolver.IsTruth(searchOptions)) { continue; } } #if DEBUG //Log("NEXT"); #endif if (sehItem.VariableName != null && !sehItem.VariableName.IsEmpty) { _currentVarStorage.SetValue(sehItem.VariableName, _currentError); } _currentError = null; _currentCodeFrame.CurrentPosition = sehItem.TargetPosition; return(true); } _currentError = null; _currentCodeFrame.CurrentPosition = _currentCodeFrame.CurrentSEHGroup.AfterPosition; return(true); }
public override void Compile() { if (index >= 0) { ilg.Emit(OpCodes.Ldc_I4, index); ilg.Emit(OpCodes.Call, getAddressMethod); // HERE ilg.Emit(OpCodes.Stloc, tmpFullCellAddr); ilg.Emit(OpCodes.Ldloca, tmpFullCellAddr); ilg.Emit(OpCodes.Call, FullCellAddr.evalMethod); } else { LoadErrorValue(ErrorValue.Make("#FUNERR: Ref to other function sheet")); } }
public MonitorState GetCurrentState() { string outputFormat = "F2"; float value = 0; MonitorState currentState = new MonitorState() { ForAgent = Description }; try { value = GetNextValue(); CurrentAgentValue = value; if (value > 9999) { outputFormat = "F0"; } else if (value > 99) { outputFormat = "F1"; } currentState.CurrentValue = value.ToString(outputFormat); currentState.State = GetState(value); currentState.CurrentValueUnit = OutputValueUnit; if (currentState.State == CollectorState.Error) { currentState.RawDetails = string.Format("(Trigger {0})", ErrorValue.ToString(outputFormat)); } else if (currentState.State == CollectorState.Warning) { currentState.RawDetails = string.Format("(Trigger {0})", WarningValue.ToString(outputFormat)); } } catch (Exception ex) { currentState.State = CollectorState.Error; if (ex.Message.Contains("Instance") && ex.Message.Contains("does not exist in the specified Category")) { currentState.CurrentValue = "Instance not found!"; } currentState.RawDetails = ex.Message; } return(currentState); }
public override Value Eval(Sheet sheet, int col, int row) { Value v = caf.Eval(); if (v is ArrayValue) { return((v as ArrayValue)[ca]); } else if (v is ErrorValue) { return(v); } else { return(ErrorValue.Make("#ERR: Not array")); } }
/// <summary> /// Check whether this CRM response represents a CRM error, and if it does /// throw it as an exception. /// </summary> /// <param name="jsonResponse">A response from CRM.</param> /// <exception cref="CrmServerErrorException">if the response was recognised as an error.</exception> private void CheckForCrmError(string jsonResponse) { ErrorValue error; try { error = DeserializeJson <ErrorValue>(jsonResponse); } catch (JsonSerializationException) { // it wasn't recognisable as an error. That's fine! error = new ErrorValue(); } if (error != null && error.IsPopulated()) { throw new CrmServerErrorException(error); } }
public static FormulaValue CountIf(EvalVisitor runner, SymbolContext symbolContext, IRContext irContext, FormulaValue[] args) { // Streaming var sources = (TableValue)args[0]; var filter = (LambdaFormulaValue)args[1]; int count = 0; var errors = new List <ErrorValue>(); foreach (var row in sources.Rows) { if (row.IsValue) { var childContext = symbolContext.WithScopeValues(row.Value); var result = filter.Eval(runner, childContext); if (result is ErrorValue error) { errors.Add(error); continue; } bool include = ((BooleanValue)result).Value; if (include) { count++; } } if (row.IsError) { errors.Add(row.Error); } } if (errors.Count != 0) { return(ErrorValue.Combine(irContext, errors)); } return(new NumberValue(irContext, count)); }
public override String ShowValue(Sheet sheet, int col, int row) { // Use the underlying cached value, do not call Eval, there might be a cycle! Value v = caf.CachedArray; if (v is ArrayValue) { Value element = (v as ArrayValue)[ca]; return(element != null?element.ToString() : ""); } else if (v is ErrorValue) { return(v.ToString()); } else { return(ErrorValue.Make("#ERR: Not array").ToString()); } }
// This is used to implement the ERR function public CGError(CGExpr[] es) { if (es.Length != 1) { errorValue = ErrorValue.argCountError; } else { CGTextConst messageConst = es[0] as CGTextConst; if (messageConst == null) { errorValue = ErrorValue.argTypeError; } else { errorValue = ErrorValue.Make("#ERR: " + messageConst.value.value); } } }
public static Func <EvalVisitor, SymbolContext, IRContext, TableValue[], FormulaValue> StandardSingleColumnTable <T>(Func <EvalVisitor, SymbolContext, IRContext, T[], FormulaValue> targetFunction) where T : FormulaValue { return((runner, symbolContext, irContext, args) => { var tableType = (TableType)irContext.ResultType; var resultType = tableType.ToRecord(); var itemType = resultType.GetFieldType(BuiltinFunction.OneColumnTableResultNameStr); var arg0 = args[0]; var resultRows = new List <DValue <RecordValue> >(); foreach (var row in arg0.Rows) { if (row.IsValue) { var value = row.Value.GetField(BuiltinFunction.ColumnName_ValueStr); NamedValue namedValue; namedValue = value switch { T t => new NamedValue(BuiltinFunction.OneColumnTableResultNameStr, targetFunction(runner, symbolContext, IRContext.NotInSource(itemType), new T[] { t })), BlankValue bv => new NamedValue(BuiltinFunction.OneColumnTableResultNameStr, bv), ErrorValue ev => new NamedValue(BuiltinFunction.OneColumnTableResultNameStr, ev), _ => new NamedValue(BuiltinFunction.OneColumnTableResultNameStr, CommonErrors.RuntimeTypeMismatch(IRContext.NotInSource(itemType))) }; var record = new InMemoryRecordValue(IRContext.NotInSource(resultType), new List <NamedValue>() { namedValue }); resultRows.Add(DValue <RecordValue> .Of(record)); } else if (row.IsBlank) { resultRows.Add(DValue <RecordValue> .Of(row.Blank)); } else { resultRows.Add(DValue <RecordValue> .Of(row.Error)); } } return new InMemoryTableValue(irContext, resultRows); }); }
public CGExtern(CGExpr[] es) : base(es, null) { if (es.Length < 1) { errorValue = ErrorValue.argCountError; } else { CGTextConst nameAndSignatureConst = es[0] as CGTextConst; if (nameAndSignatureConst == null) { errorValue = ErrorValue.argTypeError; } else { try { // This retrieves the method from cache, or creates it: ef = ExternalFunction.Make(nameAndSignatureConst.value.value); if (ef.arity != es.Length - 1) { ef = null; errorValue = ErrorValue.argCountError; } else { resType = FromType(ef.ResType); argTypes = new Typ[ef.arity]; for (int i = 0; i < argTypes.Length; i++) { argTypes[i] = FromType(ef.ArgType(i)); } } } catch (Exception exn) // Covers a multitude of sins { errorValue = ErrorValue.Make(exn.Message); } } } }
// https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-isblank-isempty // Take first non-blank value. // public static FormulaValue Coalesce(EvalVisitor runner, SymbolContext symbolContext, IRContext irContext, FormulaValue[] args) { var errors = new List <ErrorValue>(); foreach (var arg in args) { var res = runner.EvalArg <ValidFormulaValue>(arg, symbolContext, arg.IRContext); if (res.IsValue) { var val = res.Value; if (!(val is StringValue str && str.Value == "")) { if (errors.Count == 0) { return(res.ToFormulaValue()); } else { return(ErrorValue.Combine(irContext, errors)); } } } if (res.IsError) { errors.Add(res.Error); } } if (errors.Count == 0) { return(new BlankValue(irContext)); } else { return(ErrorValue.Combine(irContext, errors)); } }
protected static Gen GenLoadErrorValue(ErrorValue error) { return new Gen(delegate { LoadErrorValue(error); }); }
/// <summary> /// A pipeline that maps blanks to a value, checks /// runtime types, and possibly map values to errors /// before filtering errors and possibly returning /// an ErrorValue instead of executing /// </summary> /// <typeparam name="T">The specific FormulaValue type that the implementation of the builtin expects, for exmaple NumberValue for math functions</typeparam> /// <param name="expandArguments">This stage of the pipeline can be used to expand an argument list if some of the arguments are optional and missing</param> /// <param name="replaceBlankValues">This stage can be used to transform Blank() into something else, for example the number 0</param> /// <param name="checkRuntimeTypes">This stage can be used to check to that all the arguments have type T, or check that all arguments have type T | Blank(), etc.</param> /// <param name="checkRuntimeValues">This stage can be used to generate errors if specific values occur in the arguments, for example infinity, NaN, etc.</param> /// <param name="returnBehavior">A flag that can be used to activate pre-defined early return behavior, such as returning Blank() if any argument is Blank()</param> /// <param name="targetFunction">The implementation of the builtin function</param> /// <returns></returns> private static FunctionPtr StandardErrorHandling <T>( Func <IRContext, IEnumerable <FormulaValue>, IEnumerable <FormulaValue> > expandArguments, Func <IRContext, int, FormulaValue> replaceBlankValues, Func <IRContext, int, FormulaValue, FormulaValue> checkRuntimeTypes, Func <IRContext, int, FormulaValue, FormulaValue> checkRuntimeValues, ReturnBehavior returnBehavior, Func <EvalVisitor, SymbolContext, IRContext, T[], FormulaValue> targetFunction ) where T : FormulaValue { return((runner, symbolContext, irContext, args) => { var argumentsExpanded = expandArguments(irContext, args); var blankValuesReplaced = argumentsExpanded.Select((arg, i) => { if (arg is BlankValue) { return replaceBlankValues(arg.IRContext, i); } else { return arg; } }); var runtimeTypesChecked = blankValuesReplaced.Select((arg, i) => checkRuntimeTypes(irContext, i, arg)); var runtimeValuesChecked = runtimeTypesChecked.Select((arg, i) => { if (arg is T t) { return checkRuntimeValues(arg.IRContext, i, t); } else { return arg; } }); var errors = runtimeValuesChecked.OfType <ErrorValue>(); if (errors.Count() != 0) { return ErrorValue.Combine(irContext, errors); } switch (returnBehavior) { case ReturnBehavior.ReturnBlankIfAnyArgIsBlank: if (runtimeValuesChecked.Any(arg => arg is BlankValue)) { return new BlankValue(IRContext.NotInSource(FormulaType.Blank)); } break; case ReturnBehavior.ReturnEmptyStringIfAnyArgIsBlank: if (runtimeValuesChecked.Any(arg => arg is BlankValue)) { return new StringValue(IRContext.NotInSource(FormulaType.String), ""); } break; case ReturnBehavior.ReturnFalseIfAnyArgIsBlank: if (runtimeValuesChecked.Any(arg => arg is BlankValue)) { return new BooleanValue(IRContext.NotInSource(FormulaType.Boolean), false); } break; case ReturnBehavior.AlwaysEvaluateAndReturnResult: break; } return targetFunction(runner, symbolContext, irContext, runtimeValuesChecked.Select(arg => arg as T).ToArray()); }); }
/// <summary> /// Mathematical functions /// </summary> static Value MathOp(Env environment, Value arguments, string op) { SExprValue sexprValue = arguments.As <SExprValue>(); Debug.Assert(sexprValue != null, "Non s-expr"); // Ensure all numbers var check = ArgumentsAllOfType(sexprValue, LongValue.TYPE, op); if (check != null) { return(check); } // Pop the first element Value xBase = sexprValue.Cell[0]; LongValue x = xBase.As <LongValue>(); sexprValue.Cell.RemoveAt(0); // If no arguments and sub then perform unary negation if (op.Equals("-", StringComparison.Ordinal) && sexprValue.Cell.Count == 0) { x.Value = -x.Value; } // While there are still elements remaining while (sexprValue.Cell.Count > 0) { // Pop the next element LongValue y = sexprValue.Cell[0].As <LongValue>(); sexprValue.Cell.RemoveAt(0); if (op.Equals("+", StringComparison.Ordinal)) { x.Value += y.Value; } else if (op.Equals("-", StringComparison.Ordinal)) { x.Value -= y.Value; } else if (op.Equals("*", StringComparison.Ordinal)) { x.Value *= y.Value; } else if (op.Equals("/", StringComparison.Ordinal)) { if (y.Value == 0) { xBase = new ErrorValue("Division By Zero."); break; } x.Value /= y.Value; } else if (op.Equals("%", StringComparison.Ordinal)) { if (y.Value == 0) { xBase = new ErrorValue("Division By Zero."); break; } x.Value %= y.Value; } else if (op.Equals("^", StringComparison.Ordinal)) { x.Value = (long)Math.Pow(x.Value, y.Value); } } return(xBase); }
public static DValue <T> Of(ErrorValue error) { return(new DValue <T>(null, null, error)); }
/// <summary> /// Construct a new instance of CrmServerErrorException. /// </summary> /// <param name="error">The CRM error to wrap.</param> /// <param name="payload">The payload of the request which resulted in the error.</param> public CrmServerErrorException(ErrorValue error, string payload) : base($"CRM Server error {error.number} ({error.name}): {error.description}; request payload: {payload}") { this.payload = payload; }
protected static void LoadErrorValue(ErrorValue error) { ilg.Emit(OpCodes.Ldc_I4, error.index); ilg.Emit(OpCodes.Call, ErrorValue.fromIndexMethod); }
public Error(String msg) : this(ErrorValue.Make(msg)) { }
public Error(ErrorValue value) { this.value = value; this.error = this.value.ToString(); }
public CGError(String message) : this(ErrorValue.Make(message)) { }
private DValue(T value, BlankValue blank, ErrorValue error) { _value = value; _blank = blank; _error = error; }
protected static void LoadErrorNan(ErrorValue error) { ilg.Emit(OpCodes.Ldc_R8, error.ErrorNan); }
/// <summary> /// Construct a new instance of CrmServerErrorException. /// </summary> /// <param name="error">The CRM error to wrap.</param> public CrmServerErrorException(ErrorValue error) : base($"CRM Server error {error.number} ({error.name}): {error.description}") { this.Error = error; }
// Main method. It simply copies an unmamaged buffer to the remote process, sends the message, and then // copies the remote buffer back to the local unmanaged buffer. internal static bool XSend (IntPtr hwnd, int uMsg, IntPtr ptrStructure1, IntPtr ptrStructure2, int cbSize1, int cbSize2, ErrorValue errorCode) { using (SafeProcessHandle hProcess = new SafeProcessHandle(hwnd)) { if (hProcess.IsInvalid) { // assume that the hwnd was bad throw new ElementNotAvailableException(); } using (RemoteMemoryBlock rmem1 = new RemoteMemoryBlock(cbSize1, hProcess)) { // Ensure proper allocation if (rmem1.IsInvalid) { return false; } using (RemoteMemoryBlock rmem2 = new RemoteMemoryBlock(cbSize2, hProcess)) { // Ensure proper allocation if (rmem2.IsInvalid) { return false; } // Copy the struct to the remote process... rmem1.WriteTo(ptrStructure1, new IntPtr(cbSize1)); rmem2.WriteTo(ptrStructure2, new IntPtr(cbSize2)); // Send the message... IntPtr res = Misc.ProxySendMessage(hwnd, uMsg, rmem1.Address, rmem2.Address); // check the result if ((errorCode != ErrorValue.NoCheck) && ((errorCode == ErrorValue.Zero && res == IntPtr.Zero) || (errorCode == ErrorValue.NotZero && res != IntPtr.Zero))) { return false; } // Copy returned struct back to local process... rmem1.ReadFrom(ptrStructure1, new IntPtr(cbSize1)); rmem2.ReadFrom(ptrStructure2, new IntPtr(cbSize2)); } } } return true; }