public static bool IsBetweenIntegerExpression(IScriptCallContext context, long lower, NumericLimitType op1, long value, NumericLimitType op2, long upper)
        {
            bool result = true;

            switch (op1)
            {
            case NumericLimitType.Exclude:
                result &= (value > lower);
                break;

            case NumericLimitType.Include:
            case NumericLimitType.Approx:
                result &= (value >= lower);
                break;

            default:
                throw new NotImplementedException();
            }
            switch (op1)
            {
            case NumericLimitType.Exclude:
                result &= (value < upper);
                break;

            case NumericLimitType.Include:
            case NumericLimitType.Approx:
                result &= (value <= upper);
                break;

            default:
                throw new NotImplementedException();
            }

            return(result);
        }
        public static IProcedureReference <T> GetPartnerReference <T>(
            IScriptCallContext context, IFileElement element, string partnerName)
        {
            Type t = typeof(T);
            var  e = element;

            while (e != null)
            {
                var partner = e.ListPartners().FirstOrDefault(p => p.Name.Equals(partnerName, StringComparison.InvariantCulture));
                if (partner != null)
                {
                    System.Diagnostics.Debug.WriteLine("Expected type: " + typeof(T).FullName);
                    System.Diagnostics.Debug.WriteLine("Found type:    " + partner.ProcedureReference.ProcedureReference.GetType().GetGenericArguments()[0].FullName);
                    if (partner.ProcedureReference.ProcedureReference is IProcedureReference <T> )
                    {
                        return(partner.ProcedureReference.ProcedureReference as IProcedureReference <T>);
                    }
                    else
                    {
                        context.ReportError("The partner procedure is not the expected type.");
                        return(null);
                    }
                }
                e = e.BaseElement;
            }
            context.ReportError($"The element \"{element.FullName}\" has no partner named \"{partnerName}\".");
            return(null);
        }
 public static object ExecuteDynamicObjectMethod(
     IScriptCallContext context,
     IDynamicStepBroObject instance,
     string name,
     object[] arguments)
 {
     try
     {
         if (context != null && context.LoggingEnabled)
         {
             context.Log($"Calling dynamic method \"{name}\".");
         }
         return(instance.TryInvokeMethod(name, arguments));
     }
     catch (DynamicMethodNotFoundException)
     {
         if (context != null)
         {
             context.ReportError(
                 $"Method named '{name}' was not found on the object of type '{instance.GetType().Name}'.",
                 new DynamicMethodNotFoundError());
         }
         throw;
     }
     catch (Exception ex)
     {
         if (context != null)
         {
             context.ReportError(
                 $"Exception executing method '{name}' on the object of type '{instance.GetType().Name}'.",
                 exception: ex);
         }
         throw;
     }
 }
 public static void ProcLog2Procedure(IScriptCallContext context)
 {
     //context.Setup(ProcLog2ForceAlways, ContextLogOption.ForceAlways, true);
     if (context.LoggingEnabled)
     {
         context.Logger.Log("Step 2.1", "Normal");
     }
     if (context.LoggingEnabled && context.Logger.IsDebugging)
     {
         context.Logger.Log("Step 2.2", "Debugging");
     }
     foreach (ContextLogOption lo in Enum.GetValues(typeof(ContextLogOption)))
     {
         context.Logger.Log("Step 2.3", "Mode: " + lo.ToString());
         using (var callcontext = context.EnterNewScriptContext(ProcLog3ForceAlways, lo, false).Disposer())
         {
             ProcLog3Procedure(callcontext.Value);
         }
         using (var callcontext = context.EnterNewScriptContext(ProcLog3Normal, lo, false).Disposer())
         {
             ProcLog3Procedure(callcontext.Value);
         }
         using (var callcontext = context.EnterNewScriptContext(ProcLog3DebugOnly, lo, false).Disposer())
         {
             ProcLog3Procedure(callcontext.Value);
         }
         using (var callcontext = context.EnterNewScriptContext(ProcLog3Disabled, lo, false).Disposer())
         {
             ProcLog3Procedure(callcontext.Value);
         }
     }
 }
        public static long MyFirstProcedure(IScriptCallContext context, TimeSpan time)
        {
            //context.Setup(MyFirst, ContextLogOption.Normal, true);
            long   v1 = 17L;
            string v2 = "Mette";

            context.Logger.Log("Step 1", "");

            using (var callcontext = context.EnterNewScriptContext(MySecond, ContextLogOption.Normal, false).Disposer())
            {
                MySecondProcedure(callcontext.Value, v1, v2);
            }

            context.Logger.Log("Step 2", "");

            using (var loopStatus = context.StatusUpdater.CreateProgressReporter("Loop", TimeSpan.FromSeconds(20), 10L, p => String.Format("Iteration #{0}", p + 1L)))
            {
                for (long i = 0L; i < 10L; i++)
                {
                    context.Logger.Log("Step 3", String.Format("Loop iteration #{0}", i + 1));
                    loopStatus.UpdateStatus(progress: i + 1L);
                    using (var callcontext = context.EnterNewScriptContext(MyThird, ContextLogOption.Normal, false).Disposer())
                    {
                        MyThirdProcedure(callcontext.Value, false);
                        v1 += 2;
                    }
                }
            }

            return(v1);
        }
 public static void AwaitAsyncVoid(IScriptCallContext context, IAsyncResult result)
 {
     if (result.IsCompleted)
     {
         return;
     }
     result.AsyncWaitHandle.WaitOne();
 }
 public static T AwaitAsyncTyped <T>(IScriptCallContext context, Tasks.IAsyncResult <T> result)
 {
     if (!result.IsCompleted)
     {
         result.AsyncWaitHandle.WaitOne();
     }
     return(result.Result);
 }
 public static void LogList(IScriptCallContext context, IEnumerable <string> list)
 {
     if (list != null)
     {
         foreach (string s in list)
         {
             context.Log(s);
         }
     }
 }
        public static bool ProcedureReferenceIs(IScriptCallContext context, IProcedureReference procedure, int fileID, int procedureID, bool isNot)
        {
            var type = GetProcedure(context, fileID, procedureID);

            if (Object.ReferenceEquals(procedure, type))
            {
                return(!isNot);
            }
            return(false);
        }
        public static IFileElement GetFileElement(IScriptCallContext context, int id)
        {
            var element = ((ScriptFile)context.Self.ParentFile).GetFileElement(id);

            if (element == null)
            {
                context.ReportError(String.Format("INTERNAL ERROR: Could not find procedure with id = {0}.", id));
            }
            return(element);
        }
 public static void ProcL3Procedure(IScriptCallContext context)
 {
     if (context.LoggingEnabled)
     {
         context.Logger.Log("Step 3.1", "Normal");
     }
     if (context.LoggingEnabled && context.Logger.IsDebugging)
     {
         context.Logger.Log("Step 3.2", "Debugging");
     }
 }
 public static bool PostProcedureCallResultHandling(IScriptCallContext context, IScriptCallContext sub)
 {
     if ((context.Self.Flags & ProcedureFlags.NoSubResultInheritance) == ProcedureFlags.None)
     {
         return(context.SetResultFromSub(sub));
     }
     else
     {
         return(false);
     }
 }
 public static IProcedureReference <T> CastToSpecificProcedureType <T>(IScriptCallContext context, IProcedureReference reference)
 {
     if (reference is IProcedureReference <T> )
     {
         return((IProcedureReference <T>)reference);
     }
     else
     {
         context.ReportError("The procedure reference is not the expected type. Type: " + reference.GetType().Name);
         return(null);
     }
 }
        public static IProcedureReference GetProcedure(IScriptCallContext context, int fileID, int procedureID)
        {
            IProcedureReference procedure = null;

            if (fileID < 0)
            {
                procedure = ((ScriptFile)context.Self.ParentFile).GetProcedure(procedureID);
                if (procedure == null)
                {
                    if (context != null)
                    {
                        context.ReportError(String.Format("INTERNAL ERROR: Could not find procedure with id = {0}.", procedureID));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }
            else
            {
                ScriptFile file = context.LoadedFiles.ListFiles <ScriptFile>().FirstOrDefault(f => f.UniqueID == fileID);
                if (file == null)
                {
                    if (context != null)
                    {
                        context.ReportError(String.Format("INTERNAL ERROR: Could not find script file with id = {0}.", fileID));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    procedure = file.GetProcedure(procedureID);
                    if (procedure == null)
                    {
                        if (context != null)
                        {
                            context.ReportError(String.Format("INTERNAL ERROR: Could not find procedure with id = {0}.", procedureID));
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                }
            }
            return(procedure);
        }
        public static bool EqualsWithToleranceTimespanExpression(IScriptCallContext context, bool isApprox, TimeSpan value, TimeSpan expected, TimeSpan tolerance)
        {
            if (tolerance < TimeSpan.FromTicks(0))
            {
                throw new ArgumentException("The tolerance must be a positive value.");
            }
            var tol = tolerance;

            if (isApprox)
            {
                tol = TimeSpan.FromTicks(tolerance.Ticks + APPROX_TOL_TS);
            }
            return(value >= (expected - tolerance) && value <= (expected + tolerance));
        }
 public static void DisposeObject(IScriptCallContext context, IDisposable obj)
 {
     if (obj == null)
     {
         throw new NotImplementedException();
     }
     if (obj is IScriptDisposable)
     {
         (obj as IScriptDisposable).Dispose(context);
     }
     else
     {
         obj.Dispose();
     }
 }
 public static void ProcL2Procedure(IScriptCallContext context)
 {
     if (context.LoggingEnabled)
     {
         context.Logger.Log("Step 2.1", "Normal");
     }
     if (context.LoggingEnabled && context.Logger.IsDebugging)
     {
         context.Logger.Log("Step 2.2", "Debugging");
     }
     using (var callcontext = context.EnterNewScriptContext(ProcL3, ContextLogOption.Disabled, false).Disposer())
     {
         ProcL3Procedure(callcontext.Value);
     }
 }
        public static bool EqualsWithToleranceDateTimeExpression(IScriptCallContext context, bool isApprox, DateTime value, DateTime expected, TimeSpan tolerance)
        {
            if (tolerance < TimeSpan.FromTicks(0))
            {
                throw new ArgumentException("The tolerance must be a positive value.");
            }
            var tol = tolerance;

            if (isApprox)
            {
                tol = TimeSpan.FromTicks(tolerance.Ticks + APPROX_TOL_TS);
            }
            var lower = expected - tol;
            var upper = expected + tol;

            return(value >= lower && value <= upper);
        }
 public static object DynamicFunctionCall(
     this IProcedureReference procedure,
     IScriptCallContext context,
     object[] sequencialFirstArguments,
     ArgumentList namedArguments,
     object[] sequencialLastArguments)
 {
     if (procedure == null)
     {
         throw new ArgumentNullException("procedure");
     }
     if ((procedure.ProcedureData.Flags & ProcedureFlags.IsFunction) == ProcedureFlags.None)
     {
         throw new ArgumentException("The procedure is not marked as being a function.");
     }
     throw new NotImplementedException();
 }
 public static IAsyncResult <object> ExecuteDynamicAsyncObjectMethod(
     IScriptCallContext context,
     IDynamicAsyncStepBroObject instance,
     string name,
     object[] arguments)
 {
     try
     {
         var result = instance.TryInvokeMethod(name, arguments);
         if (result != null)
         {
             if (context != null && context.LoggingEnabled)
             {
                 context.Log($"Called method \"{name}\" on object of type '{instance.GetType().Name}'.");
             }
         }
         else
         {
             if (context != null && context.LoggingEnabled)
             {
                 context.Log($"Null value returned from method \"{name}\" on object of type '{instance.GetType().Name}'.");
             }
         }
         return(result);
     }
     catch (DynamicMethodNotFoundException)
     {
         if (context != null)
         {
             context.ReportError(
                 $"Method named '{name}' was not found on the object of type '{instance.GetType().Name}'.",
                 new DynamicMethodNotFoundError());
         }
         throw;
     }
     catch (Exception ex)
     {
         if (context != null)
         {
             context.ReportError(
                 $"Exception executing method '{name}' on the object of type '{instance.GetType().Name}'.",
                 exception: ex);
         }
         throw;
     }
 }
        public static T AwaitAsyncToTyped <T>(IScriptCallContext context, Tasks.IAsyncResult <object> result)
        {
            if (result != null && !result.IsCompleted)
            {
                if (!result.AsyncWaitHandle.WaitOne(20000))       // TODO: Register this "task" and replace with loop that waits a short while.
                {
                    throw new TimeoutException($"Timeout waiting for asynchronous result in line {context.CurrentScriptFileLine}.");
                }
            }
            if (result.IsFaulted)
            {
                if (result is IObjectFaultDescriptor)
                {
                    context.ReportError("Async operation failed. Fault: " + ((IObjectFaultDescriptor)result).FaultDescription);
                }
                else
                {
                    context.ReportError("Async operation failed.");
                }
                return(default(T));
            }
            else
            {
                object v = result?.Result;
                if (v != null)
                {
                    var valueType = v.GetType();
                    if (typeof(T).IsAssignableFrom(valueType))
                    {
                        return((T)v);
                    }
                    else if (valueType == typeof(string))
                    {
                        try
                        {
                            object value = Convert.ChangeType(v, typeof(T));
                            return((T)value);
                        }
                        catch { }
                    }

                    throw new InvalidCastException($"The async result value type is \"{v.GetType().TypeName()}\", and cannot be converted into a \"{typeof(T).TypeName()}\".");
                }
            }
            return(default(T));
        }
 public static T AwaitObjectToTyped <T>(IScriptCallContext context, object result)
 {
     if (result != null && result is Tasks.IAsyncResult <object> )
     {
         return(AwaitAsyncToTyped <T>(context, (Tasks.IAsyncResult <object>)result));
     }
     else
     {
         if (result != null)
         {
             throw new InvalidCastException($"The value type is \"{result.GetType().TypeName()}\", and cannot be converted into a \"{typeof(T).TypeName()}\".");
         }
         else
         {
             throw new InvalidCastException($"The value is null, and therefore cannot be converted into a \"{typeof(T).TypeName()}\".");
         }
     }
 }
        public static object DynamicProcedureCall(
            this IProcedureReference procedure,
            IScriptCallContext context,
            PropertyBlock propertyBlock,
            object[] sequencialFirstArguments,
            ArgumentList namedArguments,
            object[] sequencialLastArguments)
        {
            if (procedure == null)
            {
                throw new ArgumentNullException("procedure");
            }


            IScriptCallContext subContext = null;

            try
            {
                subContext = context.EnterNewScriptContext(procedure, Logging.ContextLogOption.Normal, true);

                var methodInfo = ((FileProcedure)procedure.ProcedureData).DelegateType.GetMethod("Invoke");
                var arguments  = new List <object>();
                int i          = 0;
                foreach (var p in methodInfo.GetParameters())
                {
                    if (i == 0)
                    {
                        arguments.Add(subContext);
                    }
                    i++;
                }
                Delegate runtimeProcedure = ((FileProcedure)procedure.ProcedureData).RuntimeProcedure;
                return(runtimeProcedure.DynamicInvoke(arguments.ToArray()));
            }
            catch (Exception ex)
            {
                context.ReportError("Exception in dynamic procedure call.", exception: ex);
                return(null);
            }
            finally
            {
                subContext.InternalDispose();
            }
        }
        public static bool IsBetweenDecimalExpression(IScriptCallContext context, double lower, NumericLimitType op1, double value, NumericLimitType op2, double upper)
        {
            double tolerance = (upper - lower) * APPROX_TOL;

            bool result = true;

            switch (op1)
            {
            case NumericLimitType.Exclude:
                result &= (value > lower);
                break;

            case NumericLimitType.Include:
                result &= (value >= lower);
                break;

            case NumericLimitType.Approx:
                result &= (value > (lower - tolerance));
                break;

            default:
                throw new NotImplementedException();
            }
            switch (op1)
            {
            case NumericLimitType.Exclude:
                result &= (value < upper);
                break;

            case NumericLimitType.Include:
                result &= (value <= upper);
                break;

            case NumericLimitType.Approx:
                result &= (value < (upper + tolerance));
                break;

            default:
                throw new NotImplementedException();
            }

            return(result);
        }
        public static bool IsBetweenTimespanExpression(IScriptCallContext context, TimeSpan lower, NumericLimitType op1, TimeSpan value, NumericLimitType op2, TimeSpan upper)
        {
            long tolerance = APPROX_TOL_TS;

            bool result = true;

            switch (op1)
            {
            case NumericLimitType.Exclude:
                result = (value > lower);
                break;

            case NumericLimitType.Include:
                result = (value >= lower);
                break;

            case NumericLimitType.Approx:
                result = (value.Ticks > (lower.Ticks - tolerance));
                break;

            default:
                throw new NotImplementedException();
            }
            switch (op1)
            {
            case NumericLimitType.Exclude:
                result &= (value < upper);
                break;

            case NumericLimitType.Include:
                result &= (value <= upper);
                break;

            case NumericLimitType.Approx:
                result &= (value.Ticks < (upper.Ticks + tolerance));
                break;

            default:
                throw new NotImplementedException();
            }

            return(result);
        }
        /// <summary>
        /// Executes the evaluation of an expect statement.
        /// </summary>
        /// <param name="context">Execution call context.</param>
        /// <param name="evaluation">The expect statement evaluation code.</param>
        /// <param name="negativeVerdict">The verdict for negative evaluation result.</param>
        /// <param name="title">The expect statement title.</param>
        /// <param name="expected">String representation of the expectation.</param>
        /// <returns>Whether the procedure should skip the rest and return immediately.</returns>
        public static bool ExpectStatement(
            IScriptCallContext context,
            ExpectStatementEvaluationDelegate evaluation,
            Verdict negativeVerdict,
            string title,
            string expected)
        {
            bool success;

            try
            {
                string actual;
                success = evaluation(context, out actual);
                context.ReportExpectResult(title, expected, actual, success ? Verdict.Pass : negativeVerdict);

                if (success)
                {
                    return(false);
                }
                else if (negativeVerdict == Verdict.Error)
                {
                    return(true);
                }
                else
                {
                    return((context.Self.Flags & ProcedureFlags.ContinueOnFail) == ProcedureFlags.None);
                }
            }
            catch (Exception ex)
            {
                if (context != null)
                {
                    context.ReportError($"Exception thrown during expect statement execution.", exception: ex);
                }
                else
                {
                    throw;
                }

                return(true); // Do exit the procedure
            }
        }
        public static bool EqualsWithToleranceDecimalExpression(IScriptCallContext context, bool isApprox, double value, double expected, double tolerance)
        {
            if (tolerance < 0.0)
            {
                throw new ArgumentException("The tolerance must be a positive number.");
            }
            var tol = tolerance;

            if (isApprox)
            {
                if (tol == 0.0)
                {
                    tol = APPROX_TOL;
                }
                else
                {
                    tol += tolerance * APPROX_TOL;
                }
            }
            return(value >= (expected - tol) && value <= (expected + tol));
        }
Beispiel #28
0
        public bool SetResultFromSub(IScriptCallContext sub)
        {
            if (sub.Result.Verdict > m_verdict)
            {
                m_verdict = sub.Result.Verdict;
                if (sub.Result.Verdict >= Verdict.Fail)
                {
                    m_failureLine        = m_currentStatementLine;
                    m_failureID          = sub.Result.ErrorID;
                    m_failureDescription = $"Failure in called procedure \"{sub.Self.FullName}\".";

                    if (m_verdict == Verdict.Error)
                    {
                        return(true);
                    }
                    else if (m_verdict == Verdict.Fail)
                    {
                        return((m_procedure.Flags & ProcedureFlags.ContinueOnFail) == ProcedureFlags.None);
                    }
                }
            }
            return(false);
        }
 public static IValueContainer <T> GetGlobalVariable <T>(IScriptCallContext context, int id)
 {
     if (context == null)
     {
         foreach (var file in ServiceManager.Global.Get <ILoadedFilesManager>().ListFiles <ScriptFile>())
         {
             var container = file.TryGetVariableContainer <T>(id);
             if (container != null)
             {
                 return(container);
             }
         }
     }
     else
     {
         var container = ((StepBro.Core.ScriptData.ScriptFile)context.Self.ParentFile).TryGetVariableContainer <T>(id);
         if (container != null)
         {
             return(container);
         }
     }
     context.ReportError(String.Format("INTERNAL ERROR: Could not find variable container with id = {0}.", id));
     return(null);
 }
 public bool SetResultFromSub(IScriptCallContext sub)
 {
     throw new NotImplementedException();
 }