public override void Set(RuntimeContext ctx, string name, IElfObject value, IElfObject @this)
        {
            var pbag = (PropertyBag)ctx.VM.Context["iactx"];
            if (pbag.ContainsKey(name))
            {
                pbag[name] = @this.VM.Marshaller.Marshal(value);
                return;
            }

            try
            {
                base.Set(ctx, name, value, @this);
            }
            catch (ErroneousScriptRuntimeException e)
            {
                if (e.Type == ElfExceptionType.CannotResolveVariable)
                {
                    pbag.Add(name, @this.VM.Marshaller.Marshal(value));
                }
                else
                {
                    throw;
                }
            }
        }
        public override IElfObject Get(RuntimeContext ctx, string name, IElfObject @this)
        {
            var b = Vault(ctx).GetBranch(name.FromElfIdentifier());
            if (b == null)
            {
                throw new ReferencedBranchDoesNotExistException(Node(ctx), name);
            }
            else
            {
                if (b.IsFov())
                {
                    var eval = Session(ctx).Eval(b);

                    var typeToken = b.GetValue("type").ContentString;
                    var val = typeToken == "percent" ? ((double)eval) * 100 : eval;

                    var obj_t = typeToken.GetTypeFromToken();
                    var obj = (IElfObject)Activator.CreateInstance(obj_t, val);
                    obj.Bind(ctx.VM);
                    return obj;
                }
                else
                {
                    return new ScenarioNode(b);
                }
            }
        }
        public override IElfObject Get(RuntimeContext ctx, string name, IElfObject @this)
        {
            var pbag = (PropertyBag)ctx.VM.Context["iactx"];
            if (pbag.ContainsKey(name))
            {
                return @this.VM.Marshaller.Unmarshal(pbag[name]);
            }

            return base.Get(ctx, name, @this);
        }
Example #4
0
 public override void Declare(RuntimeContext ctx, string name, IElfObject @this)
 {
     if (name.Contains("."))
     {
         throw new ErroneousScriptRuntimeException(ElfExceptionType.DuplicateVariableName, ctx.VM);
     }
     else
     {
         base.Declare(ctx, name, @this);
     }
 }
Example #5
0
        public override IElfObject Get(RuntimeContext ctx, string name, IElfObject @this)
        {
            var script = (ToyScript)@this.VM.Marshaller.Marshal(@this);
            if (name.Contains("."))
            {
                // release code should feature type check here
                return @this.VM.Marshaller.Unmarshal((double)script[name]);
            }

            return base.Get(ctx, name, @this);
        }
 public override void Declare(RuntimeContext ctx, string name, IElfObject @this)
 {
     var pbag = (PropertyBag)ctx.VM.Context["iactx"];
     if (pbag.ContainsKey(name))
     {
         throw new ErroneousScriptRuntimeException(ElfExceptionType.DuplicateVariableName, ctx.VM);
     }
     else
     {
         base.Declare(ctx, name, @this);
     }
 }
Example #7
0
        public override void Set(RuntimeContext ctx, string name, IElfObject value, IElfObject @this)
        {
            var script = (ToyScript)@this.VM.Marshaller.Marshal(@this);
            if (script[name] != null)
            {
                // release code should feature type check here
                script[name] = (double)@this.VM.Marshaller.Marshal(value);
                return;
            }

            base.Set(ctx, name, value, @this);
        }
Example #8
0
        public virtual IElfObject Get(RuntimeContext ctx, string name, IElfObject @this)
        {
            var current = ctx.CallStack.Peek();
            foreach(var scope in current.Scopes)
            {
                if (scope.ContainsKey(name))
                {
                    return scope[name];
                }
            }

            throw new ErroneousScriptRuntimeException(ElfExceptionType.CannotResolveVariable, @this.VM);
        }
Example #9
0
        public override IElfObject Get(RuntimeContext ctx, string name, IElfObject @this)
        {
            var node = (ColaNode)ctx.VM.Context["cc_node"];
            var qualifiedName = name.Contains(".") ? name : node.TPath + "." + name;

            var pbag = (ParametersValues)ctx.VM.Context["cc_values"];
            if (pbag.ContainsKey(qualifiedName))
            {
                return @this.VM.Marshaller.Unmarshal(pbag[qualifiedName]);
            }

            return base.Get(ctx, name, @this);
        }
Example #10
0
        public virtual void Declare(RuntimeContext ctx, string name, IElfObject @this)
        {
            var current = ctx.CallStack.Peek();
            foreach(var scope in current.Scopes)
            {
                if (scope.ContainsKey(name))
                {
                    throw new ErroneousScriptRuntimeException(ElfExceptionType.DuplicateVariableName, @this.VM);
                }
            }

            current.Scopes.Peek().Add(name, new ElfVoid());
        }
        //throws EngineException ,KernelException
        /// <summary>
        /// 判断任务实例是否可以终止
        /// </summary>
        /// <param name="currentSession"></param>
        /// <param name="runtimeContext"></param>
        /// <param name="processInstance"></param>
        /// <param name="taskInstance"></param>
        /// <returns>true表示可以终止,false不能终止</returns>
        public Boolean taskInstanceCanBeCompleted(IWorkflowSession currentSession, RuntimeContext runtimeContext,
            IProcessInstance processInstance, ITaskInstance taskInstance)
        {
            //在Fire Workflow 中,系统默认每个子流程仅创建一个实例,所以当子流程实例完成后,SubflowTaskInstance都可以被completed
            //所以,应该直接返回true;
            return true;

            //如果系统动态创建了多个并发子流程实例,则需要检查是否存在活动的子流程实例,如果存在则返回false,否则返回true。
            //可以用下面的代码实现
            //        IPersistenceService persistenceService = runtimeContext.PersistenceService;
            //        Int32 count = persistenceService.getAliveProcessInstanceCountForParentTaskInstance(taskInstance.Id);
            //        if (count>0){
            //            return false;
            //        }else{
            //            return true;
            //        }
        }
Example #12
0
        public void Startup(IEntryPoint entryPoint)
        {
            if (Ctx != null)
            {
                throw new UnexpectedElfRuntimeException(VM, "This thread is already started");
            }
            else
            {
                Ctx = new RuntimeContext();
                Ctx.Bind(VM);
                Ctx.CallStack.Push(new NativeCallContext(entryPoint.CodePoint, entryPoint.This, entryPoint.Args));

                VM.Threads.Add(this);
                EntryPoint = entryPoint;
                ExecutionResult = new ElfVoid();
                Status = ThreadStatus.Running;
            }
        }
Example #13
0
        public void InitControllers()
        {
            controllerContext = new ControllerContext();
            controllerContext.Injector = register;
            controllerContext.Setup();

            preloadContext = new PreloadContext();
            preloadContext.Injector = register;
            preloadContext.Setup();

            longLiveContext = new LongLiveContext();
            longLiveContext.Injector = register;
            longLiveContext.Setup();

            runtimeContext = new RuntimeContext();
            runtimeContext.Injector = register;
            runtimeContext.Setup();
        }
        // throws EngineException, KernelException
        public void run(IWorkflowSession currentSession, RuntimeContext runtimeContext, IProcessInstance processInstance, ITaskInstance taskInstance)
        {
            if (taskInstance.TaskType != TaskTypeEnum.TOOL)
            {
                throw new EngineException(processInstance, taskInstance.Activity,
                        "DefaultToolTaskInstanceRunner:TaskInstance的任务类型错误,只能为TOOL类型");
            }
            Task task = taskInstance.Task;
            if (task == null)
            {
                WorkflowProcess process = taskInstance.WorkflowProcess;
                throw new EngineException(taskInstance.ProcessInstanceId, process, taskInstance.TaskId,
                        "The Task is null,can NOT start the taskinstance,");
            }
            if (((ToolTask)task).Application == null || ((ToolTask)task).Application.Handler == null)
            {
                WorkflowProcess process = taskInstance.WorkflowProcess;
                throw new EngineException(taskInstance.ProcessInstanceId, process, taskInstance.TaskId,
                        "The task.Application is null or task.Application.Handler is null,can NOT start the taskinstance,");
            }

            Object obj = runtimeContext.getBeanByName(((ToolTask)task).Application.Handler);

            if (obj == null || !(obj is IApplicationHandler))
            {
                WorkflowProcess process = taskInstance.WorkflowProcess;
                throw new EngineException(taskInstance.ProcessInstanceId, process, taskInstance.TaskId,
                        "Run tool task instance error! Not found the instance of " + ((ToolTask)task).Application.Handler + " or the instance not implements IApplicationHandler");
            }

            try
            {
                ((IApplicationHandler)obj).execute(taskInstance);
            }
            catch (Exception )
            {//TODO wmj2003 对tool类型的task抛出的错误应该怎么处理? 这个时候引擎会如何?整个流程是否还可以继续?
                throw new EngineException(processInstance, taskInstance.Activity,
                        "DefaultToolTaskInstanceRunner:TaskInstance的任务执行失败!");
            }

            ITaskInstanceManager taskInstanceManager = runtimeContext.TaskInstanceManager;
            taskInstanceManager.completeTaskInstance(currentSession, processInstance, taskInstance, null);
        }
Example #15
0
        public override void Set(RuntimeContext ctx, string name, IElfObject value, IElfObject @this)
        {
            var node = (ColaNode)ctx.VM.Context["cc_node"];
            var qualifiedName = name.Contains(".") ? name : node.TPath + "." + name;

            var pbag = (ParametersValues)ctx.VM.Context["cc_values"];
            if (pbag.ContainsKey(qualifiedName))
            {
                pbag[qualifiedName] = @this.VM.Marshaller.Marshal(value);
                return;
            }

            try
            {
                base.Set(ctx, name, value, @this);
            }
            catch (ErroneousScriptRuntimeException)
            {
                pbag.Add(new Parameter(qualifiedName), @this.VM.Marshaller.Marshal(value));
                return;
            }
        }
Example #16
0
        public override void Declare(RuntimeContext ctx, string name, IElfObject @this)
        {
            if (name.Contains("."))
            {
                // todo. is this behavior really unacceptable?
                throw new ErroneousScriptRuntimeException(ElfExceptionType.BadVariableName, ctx.VM);
            }
            else
            {
                var node = (ColaNode)ctx.VM.Context["cc_node"];
                var qualifiedName = name.Contains(".") ? name : node.TPath + "." + name;

                var pbag = (ParametersValues)ctx.VM.Context["cc_values"];
                if (pbag.ContainsKey(qualifiedName))
                {
                    throw new ErroneousScriptRuntimeException(ElfExceptionType.DuplicateVariableName, ctx.VM);
                }
                else
                {
                    base.Declare(ctx, name, @this);
                }
            }
        }
Example #17
0
 public TestFilesSource(string path, bool useSubDirectories, RuntimeContext communicator)
     : base(path, useSubDirectories, communicator)
 {
 }
 public override void Run(RuntimeContext context, IChannel channel)
 {
     while (true)
     {
         var messages = this.GetNext();
         foreach (var message in messages)
         {
             channel.Emit(message);
         }
     }
 }
        public override void Run(RuntimeContext context, IChannel channel)
        {
            IPerfCounter mainPoolCounter = PerfCounterFactory.Create(PerfCounterImplType.AutoPilot, "iperf_ex", "tds1", PerfCounterType.Number);
            IPerfCounter extraCouter = PerfCounterFactory.Create(PerfCounterImplType.Automatic, "iperf_ex", "tds2", PerfCounterType.Number);
            ProAndConsModel server = new ProAndConsModel();
            Thread serverThread = new Thread(() => server.run(2, 2));
            serverThread.Start();
            while (true)
            {
                String workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                InstrumentationHelper.Info("location", workingDir);

                mainPoolCounter.Set(server.getPoolValue());
                extraCouter.Set(server.getThreadNum());
                Thread.Sleep(500);
            }
        }
 private IBranch Node(RuntimeContext ctx) { return (IBranch)ctx.VM.Context["nodeInProgress"]; }
Example #21
0
 public static void ExecuteOn_Mapping_Through_InitMapping(XComponent.TradeCapture.UserObject.Init init, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IInitMappingInitOnMappingTransactionSenderInterface sender)
 {
     sender.GetInstrumentSnapshot(context, new GetSnapshot());
 }
Example #22
0
        public object doInWorkflowSession(RuntimeContext ctx)
        {
            WorkflowDefinition workflowDef = ctx.DefinitionService.GetTheLatestVersionOfWorkflowDefinition(wfprocessId);
            WorkflowProcess    wfProcess   = null;

            wfProcess = workflowDef.getWorkflowProcess();

            if (wfProcess == null)
            {
                throw new Exception("Workflow process NOT found,id=[" + wfprocessId + "]");
            }

            ProcessInstance processInstance = new ProcessInstance();

            processInstance.CreatorId               = creatorId;
            processInstance.ProcessId               = wfProcess.Id;
            processInstance.Version                 = workflowDef.Version;
            processInstance.DisplayName             = wfProcess.DisplayName;
            processInstance.Name                    = wfProcess.Name;
            processInstance.State                   = ProcessInstanceEnum.INITIALIZED;
            processInstance.CreatedTime             = ctx.CalendarService.getSysDate();
            processInstance.ParentProcessInstanceId = parentProcessInstanceId;
            processInstance.ParentTaskInstanceId    = parentTaskInstanceId;

            ctx.PersistenceService.SaveOrUpdateProcessInstance(
                processInstance);

            // 初始化流程变量
            List <DataField> datafields = wfProcess.DataFields;

            for (int i = 0; datafields != null && i < datafields.Count; i++)
            {
                DataField df = (DataField)datafields[i];
                if (df.DataType == DataTypeEnum.STRING)
                {
                    if (df.InitialValue != null)
                    {
                        processInstance.setProcessInstanceVariable(df.Name, df.InitialValue);
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, "");
                    }
                }
                else if (df.DataType == DataTypeEnum.INTEGER)
                {
                    if (df.InitialValue != null)
                    {
                        try
                        {
                            Int32 intValue = Int32.Parse(df.InitialValue);
                            processInstance.setProcessInstanceVariable(df.Name, intValue);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, (Int32)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.LONG)
                {
                    if (df.InitialValue != null)
                    {
                        try
                        {
                            long longValue = long.Parse(df.InitialValue);
                            processInstance.setProcessInstanceVariable(df.Name, longValue);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, (long)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.FLOAT)
                {
                    if (df.InitialValue != null)
                    {
                        float floatValue = float.Parse(df.InitialValue);
                        processInstance.setProcessInstanceVariable(df.Name, floatValue);
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, (float)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.DOUBLE)
                {
                    if (df.InitialValue != null)
                    {
                        Double doubleValue = Double.Parse(df.InitialValue);
                        processInstance.setProcessInstanceVariable(df
                                                                   .Name, doubleValue);
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, (Double)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.BOOLEAN)
                {
                    if (df.InitialValue != null)
                    {
                        Boolean booleanValue = Boolean.Parse(df.InitialValue);
                        processInstance.setProcessInstanceVariable(df.Name, booleanValue);
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, false);
                    }
                }
                else if (df.DataType == DataTypeEnum.DATETIME)
                {
                    // TODO 需要完善一下
                    if (df.InitialValue != null &&
                        df.DataPattern != null)
                    {
                        try
                        {
                            //SimpleDateFormat dFormat = new SimpleDateFormat(df.DataPattern);
                            DateTime dateTmp = DateTime.Parse(df.InitialValue);
                            processInstance.setProcessInstanceVariable(df.Name, dateTmp);
                        }
                        catch (Exception)
                        {
                            processInstance.setProcessInstanceVariable(df.Name, null);
                            //e.printStackTrace();
                        }
                    }
                    else
                    {
                        processInstance.setProcessInstanceVariable(df.Name, null);
                    }
                }
            }

            ctx.PersistenceService.SaveOrUpdateProcessInstance(
                processInstance);

            return(processInstance);
        }
 /// <summary>
 /// Executing triggeredMethod ExecuteOn_Done_Through_TransitionTrigger
 /// </summary>
 public static void ExecuteOn_Done_Through_TransitionTrigger(XComponent.BenchSimpleFork.UserObject.TransitionTrigger transitionTrigger, object object_PublicMember, object object_InternalMember, RuntimeContext context, ITransitionTriggerTransitionTriggerOnDoneTransitionTriggerSenderInterface sender)
 {
     TriggeredMethodContext.Instance.StartBench();
     for (int i = 0; i < transitionTrigger.NbInstances; i++)
     {
         sender.SendEvent(StdEnum.TriggeringRuleBench, new UserObject.TriggerTransition {
             Id = i
         });
     }
 }
Example #24
0
        public Object doInWorkflowSession(RuntimeContext ctx)
        {
            IPersistenceService persistenceService = ctx.PersistenceService;

            return(persistenceService.FindProcessInstanceById(id));
        }
Example #25
0
        public Object doInWorkflowSession(RuntimeContext ctx)
        {
            IPersistenceService persistenceService = ctx.PersistenceService;

            return(persistenceService.FindTaskInstancesForProcessInstance(processInstanceId, activityId));
        }
Example #26
0
        public Object doInWorkflowSession(RuntimeContext ctx)
        {
            IPersistenceService persistenceService = ctx.PersistenceService;

            return(persistenceService.FindWorkItemById(workItemId));
        }
Example #27
0
 public static void ExecuteOn_Mapping_Through_ReferentialNotification(XComponent.Referential.UserObject.InstrumentSnapshot instrumentSnapshot, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IReferentialNotificationInstrumentSnapshotOnMappingTransactionSenderInterface sender)
 {
     DoMapping(instrumentSnapshot, transaction, context, sender);
 }
Example #28
0
 public static void ExecuteOn_TransactionRejected_Through_Reject(XComponent.TradeCapture.UserObject.Reject reject, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IRejectRejectOnTransactionRejectedTransactionSenderInterface sender)
 {
 }
Example #29
0
        public void run(IWorkflowSession currentSession, RuntimeContext runtimeContext,
                        IProcessInstance processInstance, ITaskInstance taskInstance)// throws EngineException, KernelException
        {
            if (taskInstance.TaskType != TaskTypeEnum.SUBFLOW)
            {
                throw new EngineException(processInstance, taskInstance.Activity,
                                          "DefaultSubflowTaskInstanceRunner:TaskInstance的任务类型错误,只能为SUBFLOW类型");
            }
            Task task = taskInstance.Task;
            SubWorkflowProcess Subflow = ((SubflowTask)task).SubWorkflowProcess;

            WorkflowDefinition subWorkflowDef = runtimeContext.DefinitionService.GetTheLatestVersionOfWorkflowDefinition(Subflow.WorkflowProcessId);

            if (subWorkflowDef == null)
            {
                WorkflowProcess parentWorkflowProcess = taskInstance.WorkflowProcess;
                throw new EngineException(taskInstance.ProcessInstanceId, parentWorkflowProcess, taskInstance.TaskId,
                                          "系统中没有Id为" + Subflow.WorkflowProcessId + "的流程定义");
            }
            WorkflowProcess subWorkflowProcess = subWorkflowDef.getWorkflowProcess();

            if (subWorkflowProcess == null)
            {
                WorkflowProcess parentWorkflowProcess = taskInstance.WorkflowProcess;
                throw new EngineException(taskInstance.ProcessInstanceId, parentWorkflowProcess, taskInstance.TaskId,
                                          "系统中没有Id为" + Subflow.WorkflowProcessId + "的流程定义");
            }

            IPersistenceService persistenceService = runtimeContext.PersistenceService;

            //更改任务的状态和开始时间
            ((TaskInstance)taskInstance).State       = TaskInstanceStateEnum.RUNNING;
            ((TaskInstance)taskInstance).StartedTime = runtimeContext.CalendarService.getSysDate();
            persistenceService.SaveOrUpdateTaskInstance(taskInstance);

            IProcessInstance subProcessInstance = currentSession.createProcessInstance(subWorkflowProcess.Name, taskInstance);

            //初始化流程变量,从父实例获得初始值
            Dictionary <String, Object> processVars = ((TaskInstance)taskInstance).AliveProcessInstance.ProcessInstanceVariables;
            List <DataField>            datafields  = subWorkflowProcess.DataFields;

            for (int i = 0; datafields != null && i < datafields.Count; i++)
            {
                DataField df = (DataField)datafields[i];
                if (df.DataType == DataTypeEnum.STRING)
                {
                    if (processVars[df.Name] != null && (processVars[df.Name] is String))
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, processVars[df.Name]);
                    }
                    else if (df.InitialValue != null)
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, df.InitialValue);
                    }
                    else
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, "");
                    }
                }
                else if (df.DataType == DataTypeEnum.INTEGER)
                {
                    if (processVars[df.Name] != null && (processVars[df.Name] is Int32))
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, processVars[df.Name]);
                    }
                    else if (df.InitialValue != null)
                    {
                        try
                        {
                            Int32 intValue = Int32.Parse(df.InitialValue);
                            subProcessInstance.setProcessInstanceVariable(df.Name, intValue);
                        }
                        catch { }
                    }
                    else
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, (Int32)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.FLOAT)
                {
                    if (processVars[df.Name] != null && (processVars[df.Name] is float))
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, processVars[df.Name]);
                    }
                    else if (df.InitialValue != null)
                    {
                        float floatValue = float.Parse(df.InitialValue);
                        subProcessInstance.setProcessInstanceVariable(df.Name, floatValue);
                    }
                    else
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, (float)0);
                    }
                }
                else if (df.DataType == DataTypeEnum.BOOLEAN)
                {
                    if (processVars[df.Name] != null && (processVars[df.Name] is Boolean))
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, processVars[df.Name]);
                    }
                    else if (df.InitialValue != null)
                    {
                        Boolean booleanValue = Boolean.Parse(df.InitialValue);
                        subProcessInstance.setProcessInstanceVariable(df.Name, booleanValue);
                    }
                    else
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, false);
                    }
                }
                else if (df.DataType == DataTypeEnum.DATETIME)
                {
                    //TODO 需要完善一下 ( 父子流程数据传递——时间类型的数据还未做传递-不知道为什么?)
                    //wmj2003 20090925 补充上了
                    if (processVars[df.Name] != null && (processVars[df.Name] is DateTime))
                    {
                        subProcessInstance.setProcessInstanceVariable(df.Name, processVars[df.Name]);
                    }
                    else if (df.InitialValue != null)
                    {
                        try
                        {
                            DateTime dateTmp = DateTime.Parse(df.InitialValue);
                            subProcessInstance.setProcessInstanceVariable(df.Name, dateTmp);
                        }
                        catch
                        {
                            subProcessInstance.setProcessInstanceVariable(df.Name, null);
                        }
                    }
                }
                //TODO 应将下面这句删除!这里还需要吗?应该直接subProcessInstance.run()就可以了。
                runtimeContext.PersistenceService.SaveOrUpdateProcessInstance(subProcessInstance);
                subProcessInstance.run();
            }
        }
Example #30
0
 public DumpController(RuntimeContext runtimeContext)
 {
     _runtimeContext = runtimeContext;
 }
 private IVault Vault(RuntimeContext ctx) { return (IVault)ctx.VM.Context["vault"]; }
Example #32
0
 internal static T Access <T>(RuntimeContext context, string name)
 {
     return((T)Access(context, name));
 }
Example #33
0
        public static void ExecuteOn_Validation_Through_NewTransaction(XComponent.TradeCapture.UserObject.Transaction transaction_TriggeringEvent, XComponent.TradeCapture.UserObject.Transaction transaction_PublicMember, object object_InternalMember, RuntimeContext context, INewTransactionTransactionOnValidationTransactionSenderInterface sender)
        {
            transaction_TriggeringEvent.Id = count++;
            Validator validator = new Validator();

            if (validator.Validate(transaction_TriggeringEvent))
            {
                sender.InitMapping(context, new Init());
            }
            else
            {
                sender.ValidationError(context, new Error());
            }

            XComponent.Shared.XCClone.Clone(transaction_TriggeringEvent, transaction_PublicMember);
        }
Example #34
0
 public ModulesAnalyzer(RuntimeContext context)
     : base(context)
 {
 }
 //throws EngineException ,KernelException
 /// <summary>
 /// 判断任务实例是否可以终止
 /// </summary>
 /// <param name="currentSession"></param>
 /// <param name="runtimeContext"></param>
 /// <param name="processInstance"></param>
 /// <param name="taskInstance"></param>
 /// <returns>true表示可以终止,false不能终止</returns>
 public Boolean taskInstanceCanBeCompleted(IWorkflowSession currentSession, RuntimeContext runtimeContext,
     IProcessInstance processInstance, ITaskInstance taskInstance)
 {
     //Tool类型的TaskInstance在handler执行完后,都可以直接结束。
     return true;
 }
 public override void Set(RuntimeContext ctx, string name, IElfObject value, IElfObject @this)
 {
     // todo. temporarily not implemented
 }
Example #37
0
 public override void Open(Configuration parameters)
 {
     // get access to the state object
     _currentState = RuntimeContext.GetState(new ValueStateDescriptor <State>("state"));
 }
Example #38
0
 public static void ExecuteOn_ErrorOnMapping_Through_Error(XComponent.TradeCapture.UserObject.Error error, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IErrorErrorOnErrorOnMappingTransactionSenderInterface sender)
 {
 }
Example #39
0
 public StringDuplicateAnalyzer(RuntimeContext context) : base(context)
 {
 }
Example #40
0
 public static void ExecuteOn_TransactionRejected_Through_TimeOut(XComponent.Common.Event.DefaultEvent defaultEvent, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, ITimeOutDefaultEventOnTransactionRejectedTransactionSenderInterface sender)
 {
 }
 public override void Run(RuntimeContext context, IChannel channel)
 {
     HydraClientBenchmark clientBenchmark = new HydraClientBenchmark(TESTCONFIG.maxOutgoing);
     clientBenchmark.Start(TESTCONFIG.threadNum);
     while (true)
     {
         Observer observer = clientBenchmark.Get();
         counters.AssignFromObserver(observer);
         InstrumentationHelper.Debug(
             "report:",
             "success[-]: [counters: {0},{1},{2},{3},{4},{5},{6}]",
             observer.sendRate, observer.successRate, observer.failSendRate, observer.failResponseRate,
             observer.expiredRate, observer.keyNotFoundRate, observer.latency
             );
         Thread.Sleep(1000);
     }
 }
Example #42
0
 public static void ExecuteOn_Validation_Through_UpdateAndRetry(XComponent.TradeCapture.UserObject.UpdateAndRetry updateAndRetry, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IUpdateAndRetryUpdateAndRetryOnValidationTransactionSenderInterface sender)
 {
 }
Example #43
0
 /// <summary>
 /// Executes the task.
 /// </summary>
 /// <param name="runtimeContext">The runtime context.</param>
 /// <param name="taskContext">The task execution context.</param>
 /// <returns>The async <see cref="Task"/>.</returns>
 public Task Execute(RuntimeContext runtimeContext, TaskContext taskContext)
 {
     throw new NotSupportedException("Post-Deploy script not supported.");
 }
Example #44
0
        protected async Task <IActionResult> GetInsights(TResource resource, string pesId, string supportTopicId, string startTime, string endTime, string timeGrain)
        {
            if (!DateTimeHelper.PrepareStartEndTimeWithTimeGrain(startTime, endTime, timeGrain, out DateTime startTimeUtc, out DateTime endTimeUtc, out TimeSpan timeGrainTimeSpan, out string errorMessage))
            {
                return(BadRequest(errorMessage));
            }

            var supportTopic = new SupportTopic()
            {
                Id = supportTopicId, PesId = pesId
            };
            RuntimeContext <TResource> cxt = PrepareContext(resource, startTimeUtc, endTimeUtc, true, supportTopic);

            List <AzureSupportCenterInsight> insights = null;
            string                   error            = null;
            List <Definition>        detectorsRun     = new List <Definition>();
            IEnumerable <Definition> allDetectors     = null;

            try
            {
                supportTopicId = ParseCorrectSupportTopicId(supportTopicId);
                allDetectors   = (await ListDetectorsInternal(cxt)).Select(detectorResponse => detectorResponse.Metadata);

                var applicableDetectors = allDetectors
                                          .Where(detector => string.IsNullOrWhiteSpace(supportTopicId) || detector.SupportTopicList.FirstOrDefault(st => st.Id == supportTopicId) != null);

                var insightGroups = await Task.WhenAll(applicableDetectors.Select(detector => GetInsightsFromDetector(cxt, detector, detectorsRun)));

                insights = insightGroups.Where(group => group != null).SelectMany(group => group).ToList();
            }
            catch (Exception ex)
            {
                error = ex.GetType().ToString();
                DiagnosticsETWProvider.Instance.LogRuntimeHostHandledException(cxt.OperationContext.RequestId, "GetInsights", cxt.OperationContext.Resource.SubscriptionId,
                                                                               cxt.OperationContext.Resource.ResourceGroup, cxt.OperationContext.Resource.Name, ex.GetType().ToString(), ex.ToString());
            }


            var correlationId = Guid.NewGuid();

            bool defaultInsightReturned = false;

            // Detectors Ran but no insights
            if (!insights.Any() && detectorsRun.Any())
            {
                defaultInsightReturned = true;
                insights.Add(AzureSupportCenterInsightUtilites.CreateDefaultInsight(cxt.OperationContext, detectorsRun));
            }
            // No detectors matched this support topic
            else if (!detectorsRun.Any())
            {
                var defaultDetector = allDetectors.FirstOrDefault(detector => detector.Id.StartsWith("default_insights"));
                if (defaultDetector != null)
                {
                    var defaultDetectorInsights = await GetInsightsFromDetector(cxt, defaultDetector, new List <Definition>());

                    defaultInsightReturned = defaultDetectorInsights.Any();
                    insights.AddRange(defaultDetectorInsights);
                }
            }

            var insightInfo = new
            {
                Total    = insights.Count,
                Critical = insights.Count(insight => insight.ImportanceLevel == ImportanceLevel.Critical),
                Warning  = insights.Count(insight => insight.ImportanceLevel == ImportanceLevel.Warning),
                Info     = insights.Count(insight => insight.ImportanceLevel == ImportanceLevel.Info),
                Default  = defaultInsightReturned ? 1 : 0
            };

            DiagnosticsETWProvider.Instance.LogRuntimeHostInsightCorrelation(cxt.OperationContext.RequestId, "ControllerBase.GetInsights", cxt.OperationContext.Resource.SubscriptionId,
                                                                             cxt.OperationContext.Resource.ResourceGroup, cxt.OperationContext.Resource.Name, correlationId.ToString(), JsonConvert.SerializeObject(insightInfo));

            var response = new AzureSupportCenterInsightEnvelope()
            {
                CorrelationId      = correlationId,
                ErrorMessage       = error,
                TotalInsightsFound = insights != null?insights.Count() : 0,
                                         Insights = insights
            };

            return(Ok(response));
        }
 public Authority(RuntimeContext context)
     : this(context, DefaultAuthorityHostUrl)
 {
 }
Example #46
0
        private async Task <IEnumerable <DiagnosticApiResponse> > ListDetectorsInternal(RuntimeContext <TResource> context)
        {
            await this._sourceWatcherService.Watcher.WaitForFirstCompletion();

            return(_invokerCache.GetDetectorInvokerList <TResource>(context)
                   .Select(p => new DiagnosticApiResponse {
                Metadata = RemovePIIFromDefinition(p.EntryPointDefinitionAttribute, context.ClientIsInternal)
            }));
        }
 public void setRuntimeContext(RuntimeContext ctx)
 {
     throw new NotImplementedException();
 }
Example #48
0
        private async Task <Tuple <Response, List <DataProviderMetadata> > > GetDetectorInternal(string detectorId, RuntimeContext <TResource> context)
        {
            await this._sourceWatcherService.Watcher.WaitForFirstCompletion();

            var dataProviders = new DataProviders.DataProviders(_dataSourcesConfigService.Config);
            var invoker       = this._invokerCache.GetDetectorInvoker <TResource>(detectorId, context);

            if (invoker == null)
            {
                return(null);
            }

            Response res = new Response
            {
                Metadata = RemovePIIFromDefinition(invoker.EntryPointDefinitionAttribute, context.ClientIsInternal)
            };

            var response = (Response)await invoker.Invoke(new object[] { dataProviders, context.OperationContext, res });

            List <DataProviderMetadata> dataProvidersMetadata = null;

            response.UpdateDetectorStatusFromInsights();

            if (context.ClientIsInternal)
            {
                dataProvidersMetadata = GetDataProvidersMetadata(dataProviders);
            }

            return(new Tuple <Response, List <DataProviderMetadata> >(response, dataProvidersMetadata));
        }
 private EvalSession Session(RuntimeContext ctx) { return (EvalSession)ctx.VM.Context["evalSession"]; }
Example #50
0
        private async Task <IEnumerable <AzureSupportCenterInsight> > GetInsightsFromDetector(RuntimeContext <TResource> context, Definition detector, List <Definition> detectorsRun)
        {
            Response response = null;

            detectorsRun.Add(detector);

            try
            {
                var fullResponse = await GetDetectorInternal(detector.Id, context);

                if (fullResponse != null)
                {
                    response = fullResponse.Item1;
                }
            }
            catch (Exception ex)
            {
                DiagnosticsETWProvider.Instance.LogRuntimeHostHandledException(context.OperationContext.RequestId, "GetInsightsFromDetector", context.OperationContext.Resource.SubscriptionId,
                                                                               context.OperationContext.Resource.ResourceGroup, context.OperationContext.Resource.Name, ex.GetType().ToString(), ex.ToString());
            }

            // Handle Exception or Not Found
            // Not found can occur if invalid detector is put in detector list
            if (response == null)
            {
                return(null);
            }

            List <AzureSupportCenterInsight> supportCenterInsights = new List <AzureSupportCenterInsight>();

            if (response.AscInsights.Any())
            {
                foreach (var ascInsight in response.AscInsights)
                {
                    DiagnosticsETWProvider.Instance.LogRuntimeHostDetectorAscInsight(context.OperationContext.RequestId, detector.Id, ascInsight.ImportanceLevel.ToString(), JsonConvert.SerializeObject(ascInsight));
                    supportCenterInsights.Add(ascInsight);
                }
            }
            else
            {
                // Take max one insight per detector, only critical or warning, pick the most critical
                var mostCriticalInsight = response.Insights.OrderBy(insight => insight.Status).FirstOrDefault();

                //TODO: Add Logging Per Detector Here
                AzureSupportCenterInsight ascInsight = null;
                if (mostCriticalInsight != null)
                {
                    ascInsight = AzureSupportCenterInsightUtilites.CreateInsight(mostCriticalInsight, context.OperationContext, detector);
                    supportCenterInsights.Add(ascInsight);
                }

                DiagnosticsETWProvider.Instance.LogRuntimeHostDetectorAscInsight(context.OperationContext.RequestId, detector.Id, ascInsight?.ImportanceLevel.ToString(), JsonConvert.SerializeObject(ascInsight));
            }

            var detectorLists = response.Dataset
                                .Where(diagnosicData => diagnosicData.RenderingProperties.Type == RenderingType.Detector)
                                .SelectMany(diagnosticData => ((DetectorCollectionRendering)diagnosticData.RenderingProperties).DetectorIds)
                                .Distinct();

            if (detectorLists.Any())
            {
                var applicableDetectorMetaData = (await this.ListDetectorsInternal(context)).Where(detectorResponse => detectorLists.Contains(detectorResponse.Metadata.Id));
                var detectorListResponses      = await Task.WhenAll(applicableDetectorMetaData.Select(detectorResponse => GetInsightsFromDetector(context, detectorResponse.Metadata, detectorsRun)));

                supportCenterInsights.AddRange(detectorListResponses.Where(detectorInsights => detectorInsights != null).SelectMany(detectorInsights => detectorInsights));
            }

            return(supportCenterInsights);
        }
Example #51
0
        /// <summary>
        /// Determines whether the provided <see cref="T:System.Threading.Tasks.Task"/> can be executed synchronously in this call, and if it can, executes it.
        /// </summary>
        /// <returns>
        /// A Boolean value indicating whether the task was executed inline.
        /// </returns>
        /// <param name="task">The <see cref="T:System.Threading.Tasks.Task"/> to be executed.</param>
        /// <param name="taskWasPreviouslyQueued">A Boolean denoting whether or not task has previously been queued. If this parameter is True, then the task may have been previously queued (scheduled); if False, then the task is known not to have been queued, and this call is being made in order to execute the task inline without queuing it.</param>
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            bool canExecuteInline = WorkerPoolThread.CurrentWorkerThread != null;

            RuntimeContext ctx = RuntimeContext.Current;
            bool           canExecuteInline2 = canExecuteInline && ctx != null && object.Equals(ctx.ActivationContext, workerGroup.SchedulingContext);

            canExecuteInline = canExecuteInline2;

#if DEBUG
            if (logger.IsVerbose2)
            {
                logger.Verbose2(myId + " --> TryExecuteTaskInline Task Id={0} Status={1} PreviouslyQueued={2} CanExecute={3} Queued={4}",
                                task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline, workerGroup.ExternalWorkItemCount);
            }
#endif
            if (!canExecuteInline)
            {
                return(false);
            }

            // If the task was previously queued, remove it from the queue
            if (taskWasPreviouslyQueued)
            {
                canExecuteInline = TryDequeue(task);
            }


            if (!canExecuteInline)
            {
#if DEBUG
                if (logger.IsVerbose2)
                {
                    logger.Verbose2(myId + " <-X TryExecuteTaskInline Task Id={0} Status={1} Execute=No", task.Id, task.Status);
                }
#endif
                return(false);
            }

#if EXTRA_STATS
            turnsExecutedStatistic.Increment();
#endif
#if DEBUG
            if (logger.IsVerbose3)
            {
                logger.Verbose3(myId + " TryExecuteTaskInline Task Id={0} Thread={1} Execute=Yes", task.Id, Thread.CurrentThread.ManagedThreadId);
            }
#endif
            // Try to run the task.
            bool done = TryExecuteTask(task);
            if (!done)
            {
                logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete3, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
                            task.Id, task.Status);
            }
#if DEBUG
            if (logger.IsVerbose2)
            {
                logger.Verbose2(myId + " <-- TryExecuteTaskInline Task Id={0} Thread={1} Execute=Done Ok={2}", task.Id, Thread.CurrentThread.ManagedThreadId, done);
            }
#endif
            return(done);
        }
Example #52
0
 public static void ExecuteOn_TransactionAccepted_Through_Accepted(XComponent.TradeCapture.UserObject.Accept accept, XComponent.TradeCapture.UserObject.Transaction transaction, object object_InternalMember, RuntimeContext context, IAcceptedAcceptOnTransactionAcceptedTransactionSenderInterface sender)
 {
 }
Example #53
0
 /// <summary>
 /// Executing triggeredMethod ExecuteOn_Published_Through_PublishResult
 /// </summary>
 public static void ExecuteOn_Published_Through_PublishResult(XComponent.BenchSimpleFork.UserObject.BenchResult benchResult_TriggeringEvent, XComponent.BenchSimpleFork.UserObject.BenchResult benchResult_PublicMember, object object_InternalMember, RuntimeContext context, IPublishResultBenchResultOnPublishedBenchResultSenderInterface sender)
 {
     // Uncomment the following line if you want to copy benchResult_TriggeringEvent properties values into benchResult_PublicMember
     XComponent.Shared.XCClone.Clone(benchResult_TriggeringEvent, benchResult_PublicMember);
 }
Example #54
0
        private static WorkItemRepositoryMock MakeRepository(out IWorkItem startPoint)
        {
            var logger     = Substitute.For <ILogEvents>();
            var settings   = TestHelpers.LoadConfigFromResourceFile("NewObjects.policies", logger);
            var repository = new WorkItemRepositoryMock();

            System.Func <IRuntimeContext, IScriptLibrary> scriptLibraryBuilder = (x) => Substitute.For <IScriptLibrary>();
            var context = Substitute.For <IRequestContext>();

            context.GetProjectCollectionUri().Returns(
                new System.Uri("http://localhost:8080/tfs/DefaultCollection"));
            var runtime = RuntimeContext.MakeRuntimeContext("settingsPath", settings, context, logger, (c) => repository, scriptLibraryBuilder);

            var grandParent = new WorkItemMock(repository, runtime);

            grandParent.Id       = 1;
            grandParent.TypeName = "Requirement";
            grandParent["Microsoft.VSTS.Scheduling.RemainingWork"] = 2.0;

            var parent = new WorkItemMock(repository, runtime);

            parent.Id       = 2;
            parent.TypeName = "Use Case";

            var firstChild = new WorkItemMock(repository, runtime);

            firstChild.Id       = 3;
            firstChild.TypeName = "Task";
            var secondChild = new WorkItemMock(repository, runtime);

            secondChild.Id       = 4;
            secondChild.TypeName = "Task";

            var tc1 = new WorkItemMock(repository, runtime);

            tc1.Id       = 21;
            tc1.TypeName = "Test Case";
            tc1["Microsoft.VSTS.Scheduling.RemainingWork"] = 10.0;
            var tc2 = new WorkItemMock(repository, runtime);

            tc2.Id       = 22;
            tc2.TypeName = "Test Case";
            tc2["Microsoft.VSTS.Scheduling.RemainingWork"] = 30.0;

            firstChild.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ParentRelationship, parent.Id, repository));
            secondChild.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ParentRelationship, parent.Id, repository));
            parent.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ParentRelationship, grandParent.Id, repository));

            grandParent.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ChildRelationship, parent.Id, repository));
            parent.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ChildRelationship, firstChild.Id, repository));
            parent.WorkItemLinksImpl.Add(new WorkItemLinkMock(WorkItemImplementationBase.ChildRelationship, secondChild.Id, repository));

            // Tested By
            grandParent.WorkItemLinksImpl.Add(new WorkItemLinkMock("Microsoft.VSTS.Common.TestedBy-Forward", tc1.Id, repository));

            // Tests
            tc1.WorkItemLinksImpl.Add(new WorkItemLinkMock("Microsoft.VSTS.Common.TestedBy-Reverse", grandParent.Id, repository));

            // Tested By
            grandParent.WorkItemLinksImpl.Add(new WorkItemLinkMock("Microsoft.VSTS.Common.TestedBy-Forward", tc2.Id, repository));

            // Tests
            tc2.WorkItemLinksImpl.Add(new WorkItemLinkMock("Microsoft.VSTS.Common.TestedBy-Reverse", grandParent.Id, repository));

            repository.SetWorkItems(new[] { grandParent, parent, firstChild, secondChild, tc1, tc2 });

            startPoint = grandParent;
            return(repository);
        }
Example #55
0
 public virtual void LeaveScope(RuntimeContext ctx, IElfObject @this)
 {
     ctx.CallStack.Peek().Scopes.Pop();
 }
Example #56
0
        protected async Task <IActionResult> ExecuteQuery <TPostBodyResource>(TResource resource, CompilationBostBody <TPostBodyResource> jsonBody, string startTime, string endTime, string timeGrain, string detectorId = null, string dataSource = null, string timeRange = null)
        {
            if (jsonBody == null)
            {
                return(BadRequest("Missing body"));
            }

            if (string.IsNullOrWhiteSpace(jsonBody.Script))
            {
                return(BadRequest("Missing script in body"));
            }

            if (!DateTimeHelper.PrepareStartEndTimeWithTimeGrain(startTime, endTime, timeGrain, out DateTime startTimeUtc, out DateTime endTimeUtc, out TimeSpan timeGrainTimeSpan, out string errorMessage))
            {
                return(BadRequest(errorMessage));
            }

            await this._sourceWatcherService.Watcher.WaitForFirstCompletion();

            EntityMetadata metaData      = new EntityMetadata(jsonBody.Script);
            var            dataProviders = new DataProviders.DataProviders(_dataSourcesConfigService.Config);

            QueryResponse <DiagnosticApiResponse> queryRes = new QueryResponse <DiagnosticApiResponse>
            {
                InvocationOutput = new DiagnosticApiResponse()
            };

            Assembly tempAsm = null;

            this.Request.Headers.TryGetValue(HeaderConstants.RequestIdHeaderName, out StringValues requestIds);
            var compilerResponse = await _compilerHostClient.GetCompilationResponse(jsonBody.Script, requestIds.FirstOrDefault() ?? string.Empty);

            queryRes.CompilationOutput = compilerResponse;

            if (queryRes.CompilationOutput.CompilationSucceeded)
            {
                byte[] asmData = Convert.FromBase64String(compilerResponse.AssemblyBytes);
                byte[] pdbData = Convert.FromBase64String(compilerResponse.PdbBytes);

                tempAsm = Assembly.Load(asmData, pdbData);

                using (var invoker = new EntityInvoker(metaData, ScriptHelper.GetFrameworkReferences(), ScriptHelper.GetFrameworkImports()))
                {
                    invoker.InitializeEntryPoint(tempAsm);

                    // Verify Detector with other detectors in the system in case of conflicts
                    List <DataProviderMetadata> dataProvidersMetadata = null;
                    Response invocationResponse = null;
                    bool     isInternalCall     = true;
                    try
                    {
                        if (detectorId == null)
                        {
                            if (!VerifyEntity(invoker, ref queryRes))
                            {
                                return(Ok(queryRes));
                            }
                            RuntimeContext <TResource> cxt = PrepareContext(resource, startTimeUtc, endTimeUtc);

                            var responseInput = new Response()
                            {
                                Metadata = RemovePIIFromDefinition(invoker.EntryPointDefinitionAttribute, cxt.ClientIsInternal)
                            };
                            invocationResponse = (Response)await invoker.Invoke(new object[] { dataProviders, cxt.OperationContext, responseInput });

                            invocationResponse.UpdateDetectorStatusFromInsights();
                            isInternalCall = cxt.ClientIsInternal;
                        }
                        else
                        {
                            Dictionary <string, dynamic> systemContext = PrepareSystemContext(resource, detectorId, dataSource, timeRange);
                            var responseInput = new Response()
                            {
                                Metadata = invoker.EntryPointDefinitionAttribute
                            };
                            invocationResponse = (Response)await invoker.Invoke(new object[] { dataProviders, systemContext, responseInput });
                        }

                        if (isInternalCall)
                        {
                            dataProvidersMetadata = GetDataProvidersMetadata(dataProviders);
                        }

                        queryRes.RuntimeSucceeded = true;
                        queryRes.InvocationOutput = DiagnosticApiResponse.FromCsxResponse(invocationResponse, dataProvidersMetadata);
                    }
                    catch (Exception ex)
                    {
                        if (isInternalCall)
                        {
                            queryRes.RuntimeSucceeded = false;
                            queryRes.InvocationOutput = CreateQueryExceptionResponse(ex, invoker.EntryPointDefinitionAttribute, isInternalCall, GetDataProvidersMetadata(dataProviders));
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            return(Ok(queryRes));
        }
Example #57
0
 public virtual void EnterScope(RuntimeContext ctx, IElfObject @this)
 {
     ctx.CallStack.Peek().Scopes.Push(new Scope());
 }
 public virtual void PrepareCallContext(RuntimeContext ctx, string name, IElfObject @this, params IElfObject[] args)
 {
     var resolved = Resolve(@this.VM, name, @this.Type, args.Select(arg => arg.Type).ToArray());
     if (resolved == null)
     {
         throw new ErroneousScriptRuntimeException(ElfExceptionType.CannotResolveInvocation, ctx.VM);
     }
     else
     {
         if (resolved is NativeMethod)
         {
             // this class, elf method
             if (resolved.Argc == args.Length)
             {
                 ctx.CallStack.Push(new NativeCallContext(
                     (NativeMethod)resolved, @this, args));
             }
             // other class, elf method as well
             else
             {
                 ctx.CallStack.Push(new NativeCallContext(
                     (NativeMethod)resolved, args[0], args.Skip(1).ToArray()));
             }
         }
         else
         {
             var mi = ((ClrMethod)resolved).Rtimpl;
             if (mi.DeclaringType != @this.Type.ClrType)
             {
                 if (mi.IsConstructor)
                 {
                     // other class, clr ctor
                     ctx.PendingClrCall = new ClrCallContext(
                          (ClrMethod)resolved, null, args);
                 }
                 else if (mi.IsStatic)
                 {
                     // other class, static clr method
                     ctx.PendingClrCall = new ClrCallContext(
                          (ClrMethod)resolved, args[0], args);
                 }
                 else
                 {
                     // other class, instance clr method
                     ctx.PendingClrCall = new ClrCallContext(
                         (ClrMethod)resolved, args[0], args.Skip(1).ToArray());
                 }
             }
             else
             {
                 if (mi.IsStatic)
                 {
                     // this class, static clr method
                     ctx.PendingClrCall = new ClrCallContext(
                          (ClrMethod)resolved, @this, @this.AsArray().Concat(args).ToArray());
                 }
                 else
                 {
                     // this class, instance clr method
                     ctx.PendingClrCall = new ClrCallContext(
                         (ClrMethod)resolved, @this, args);
                 }
             }
         }
     }
 }