Ejemplo n.º 1
0
        /// <inheritdoc />
        public Task Send(MailMessage message)
        {
            var  data   = new Dictionary <string, object>();
            bool cancel = false;

            // run pre process interceptors
            foreach (var interceptor in interceptors)
            {
                interceptor.Sending(message, data, ref cancel);
                if (cancel)
                {
                    return(Task.CompletedTask);
                }
            }

            // send email and run post process interceptors
            return(ExecutionStrategy.Execute(Process, message, data, CancellationToken).ContinueWith((task) =>
            {
                if (task.IsFaulted == false)
                {
                    foreach (var interceptor in interceptors)
                    {
                        interceptor.Sent(message, data);
                    }
                }
            }));
        }
Ejemplo n.º 2
0
        private void onNewInstanceCreated(ActiveInstance activeInstance)
        {
            newInstanceSet.Add(activeInstance);
            ExecutionStrategy ex = activeInstance.IndexedMType.Type.ExecutionStrategy;

            while (ex != null && ex.Rules.Count == 0)
            {
                ex = ex.Next;
            }

            if (ex != null)
            {
                allOperationalInstances.Add(activeInstance);
            }

            if (RegisterNewInstance != null)
            {
                RegisterNewInstance(activeInstance.Instance);
            }

            if (step >= startStep)
            {
                if (recordInstanceCreation)
                {
                    if (NewInstanceCreated != null)
                    {
                        NewInstanceCreated(activeInstance.Instance, activeInstance.Type);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public List <int> Guards(ExecutionStrategy es)
        {
            List <int> list = new List <int>();
            List <int> pos  = new List <int>();

            foreach (Rule r in es.Rules)
            {
                if (r.Guard != null)
                {
                    pos.Add(list.Count);
                    List <int> g = new List <int>();
                    Guard(g, r.Guard);
                    list.AddRange(g);
                    list.Add(-1);
                }
                else
                {
                    pos.Add(-1);
                }
            }
            int n = es.Rules.Count;

            pos = pos.Select(a => a > -1 ? a + n + 1:0).ToList();
            pos.Insert(0, n);
            list.InsertRange(0, pos);
            return(list);
        }
Ejemplo n.º 4
0
        private void Dispatch(WorkItem work, ExecutionStrategy strategy)
        {
            log.Debug("Using {0} strategy for {1}", strategy, work.Name);

            switch (strategy)
            {
            default:
            case ExecutionStrategy.Direct:
                work.Execute();
                break;

            case ExecutionStrategy.Parallel:
                if (work.TargetApartment == ApartmentState.STA)
                {
                    ParallelSTAQueue.Enqueue(work);
                }
                else
                {
                    ParallelQueue.Enqueue(work);
                }
                break;

            case ExecutionStrategy.NonParallel:
                if (work.TargetApartment == ApartmentState.STA)
                {
                    NonParallelSTAQueue.Enqueue(work);
                }
                else
                {
                    NonParallelQueue.Enqueue(work);
                }
                break;
            }
        }
Ejemplo n.º 5
0
        public void ExtendedRootTypesWillHonorGlobalSerialSetting(ExecutionStrategy defaultStrategy)
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .AddQueryType(c => c.Name(OperationTypeNames.Query))
                             .AddType <BarQueries>()
                             .ModifyOptions(o => o.DefaultResolverStrategy = defaultStrategy)
                             .Create();

            DocumentNode document = Utf8GraphQLParser.Parse(
                @"{
                    bars
                }");

            OperationDefinitionNode operationDefinition =
                document.Definitions.OfType <OperationDefinitionNode>().Single();

            IPreparedOperation operation =
                OperationCompiler.Compile(
                    "a",
                    document,
                    operationDefinition,
                    schema,
                    schema.QueryType,
                    new(new DefaultTypeConverter()));

            // act
            QueryPlanNode root = QueryPlanBuilder.Prepare(operation);

            // assert
            Snapshot(root, defaultStrategy);
        }
Ejemplo n.º 6
0
        public void CreateReviewForEpisode_Plan(ExecutionStrategy defaultStrategy)
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .AddStarWarsTypes()
                             .ModifyOptions(o => o.DefaultResolverStrategy = defaultStrategy)
                             .Create();

            DocumentNode document = Utf8GraphQLParser.Parse(
                @"mutation CreateReviewForEpisode(
                    $ep: Episode!, $review: ReviewInput!) {
                    createReview(episode: $ep, review: $review) {
                        stars
                        commentary
                    }
                }");

            OperationDefinitionNode operationDefinition =
                document.Definitions.OfType <OperationDefinitionNode>().Single();

            IPreparedOperation operation =
                OperationCompiler.Compile(
                    "a",
                    document,
                    operationDefinition,
                    schema,
                    schema.MutationType !,
                    new(new DefaultTypeConverter()));

            // act
            QueryPlanNode root = QueryPlanBuilder.Prepare(operation);

            // assert
            Snapshot(root, defaultStrategy);
        }
Ejemplo n.º 7
0
        public void ParallelAttributeWillBeHonored(ExecutionStrategy defaultStrategy)
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .AddQueryType <ParallelQuery>()
                             .Create();

            DocumentNode document = Utf8GraphQLParser.Parse(
                @"{
                    foo
                }");

            OperationDefinitionNode operationDefinition =
                document.Definitions.OfType <OperationDefinitionNode>().Single();

            IPreparedOperation operation =
                OperationCompiler.Compile(
                    "a",
                    document,
                    operationDefinition,
                    schema,
                    schema.QueryType,
                    new(new DefaultTypeConverter()));

            // act
            QueryPlanNode root = QueryPlanBuilder.Prepare(operation);

            // assert
            Snapshot(root, defaultStrategy);
        }
Ejemplo n.º 8
0
        public override void Dispose()
        {
            _executionStrategy = null;
            _messageBus        = null;

            base.Dispose();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 创建定时任务
        /// </summary>
        /// <param name="crontabType">定时任务类型</param>
        /// <param name="strategy">执行策略</param>
        /// <returns>定时任务</returns>
        public static ICrontab CreateCrontab(Type crontabType, ExecutionStrategy strategy)
        {
            #region # 验证

            if (crontabType == null)
            {
                throw new ArgumentNullException(nameof(crontabType), "定时任务类型不可为空!");
            }
            if (strategy == null)
            {
                throw new ArgumentNullException(nameof(strategy), "执行策略不可为空!");
            }
            if (!typeof(ICrontab).IsAssignableFrom(crontabType))
            {
                throw new ArgumentOutOfRangeException(nameof(crontabType), "给定类型不是定时任务类型!");
            }

            #endregion

            object instance = Activator.CreateInstance(crontabType, strategy);

            #region # 验证

            if (instance == null)
            {
                throw new NullReferenceException("给定类型的定时任务不存在!");
            }

            #endregion

            ICrontab crontab = (ICrontab)instance;

            return(crontab);
        }
Ejemplo n.º 10
0
        public static void generateDivisionRules(MType type, Module paramModule)
        {
            if (paramModule != null)
            {
                module = paramModule;
            }
            //get all division rules
            List <KpCore.Rule> divisionRules = new List <KpCore.Rule>();
            ExecutionStrategy  eS            = type.ExecutionStrategy;

            while (eS != null)
            {
                foreach (var rule in eS.Rules)
                {
                    if (rule.Type == RuleType.MEMBRANE_DIVISION)
                    {
                        divisionRules.Add(rule);
                    }
                }
                eS = eS.Next;
            }
            if (divisionRules.Count > 0)
            {
                //or each parent instance, generate a permutation of rules.
                ParentInstance parentInstance = null;
                Instance       smvInstance    = module.Instance;
                if (smvInstance.DivisionType == DIVISIONTYPE.PARENT)
                {
                    parentInstance = (ParentInstance)smvInstance;
                    generateDivisionInstances(parentInstance, divisionRules);
                }
            }
        }
Ejemplo n.º 11
0
        private static IResolveFieldContext CreateResolveFieldContext(ISchema schema, string query)
        {
            var documentBuilder = new GraphQLDocumentBuilder();
            var document        = documentBuilder.Build(query);

            schema.Initialize();

            var executionContext = new ExecutionContext
            {
                Document  = document,
                Schema    = schema,
                Fragments = document.Fragments,
                Operation = document.Operations.First()
            };

            var root = new RootExecutionNode(schema.Query)
            {
                Result = executionContext.RootValue
            };

            var fields = ExecutionHelper.CollectFields(executionContext, schema.Query, executionContext.Operation.SelectionSet);

            ExecutionStrategy.SetSubFieldNodes(executionContext, root, fields);

            var subNode = root.SubFields.FirstOrDefault();

            return(new ReadonlyResolveFieldContext(subNode.Value, executionContext));
        }
Ejemplo n.º 12
0
        /// <inheritdoc />
        public Task SendAsync(MailMessage message)
        {
            var  data   = new Dictionary <string, object>();
            bool cancel = false;

            // Run pre process interceptors.
            foreach (var interceptor in interceptors)
            {
                interceptor.Sending(message, data, ref cancel);
                if (cancel)
                {
#if NET452
                    var tcs = new TaskCompletionSource <bool>();
                    tcs.SetResult(true);
                    return(tcs.Task);
#else
                    return(Task.CompletedTask);
#endif
                }
            }

            // Send email and run post process interceptors.
            return(ExecutionStrategy.Execute(Process, message, data, CancellationToken).ContinueWith(task =>
            {
                if (!task.IsFaulted)
                {
                    foreach (var interceptor in interceptors)
                    {
                        interceptor.Sent(message, data);
                    }
                }
            }, CancellationToken));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 无参构造器
 /// </summary>
 protected Crontab(ExecutionStrategy executionStrategy)
 {
     //默认值
     this.Id                = Guid.NewGuid().ToString();
     this.AddedTime         = DateTime.Now;
     this.ExecutionStrategy = executionStrategy;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ActiveClient(ClientId id)
        {
            _id = id;

            _executionStrategy = null;
            _messageBus        = null;
        }
Ejemplo n.º 15
0
        public IWhenDoCommand CreateCommandFromDefinition(CommandDefinition definition, List <ExpressionProviderInfo> providerInfos)
        {
            ExecutionStrategy strategy = null;

            if (definition.Execution.Mode == ExecutionMode.Default || definition.Execution.Mode == ExecutionMode.Reliable)
            {
                strategy = new ExecutionStrategy()
                {
                    Mode = definition.Execution.Mode, Time = null
                }
            }
            ;
            else
            {
                strategy = CreateExecutionStrategyFromDefinition(definition.Execution, providerInfos);
            }

            var command = new WhenDoCommand()
            {
                Id                = Guid.NewGuid().ToString("N").ToLower(),
                Type              = definition.Type,
                MethodName        = definition.Command,
                Parameters        = definition.Parameters,
                ExecutionStrategy = strategy
            };

            return(command);
        }
Ejemplo n.º 16
0
        //Private

        #region # 获取触发器 —— static ITrigger GetTrigger(ExecutionStrategy strategy)
        /// <summary>
        /// 获取触发器
        /// </summary>
        /// <param name="strategy">执行策略</param>
        /// <returns>触发器</returns>
        private static ITrigger GetTrigger(ExecutionStrategy strategy)
        {
            if (strategy is FixedTimeStrategy fixedTimeStrategy)
            {
                string   cronExpression = fixedTimeStrategy.TriggerTime.ToCronExpression();
                ITrigger trigger        = TriggerBuilder.Create().WithCronSchedule(cronExpression).Build();

                return(trigger);
            }
            if (strategy is RepeatedTimeStrategy repeatedTimeStrategy)
            {
                string   cronExpression = repeatedTimeStrategy.TriggerTime.ToCronExpression();
                ITrigger trigger        = TriggerBuilder.Create().WithCronSchedule(cronExpression).Build();

                return(trigger);
            }
            if (strategy is RecurrenceStrategy recurrenceStrategy)
            {
                ITrigger trigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithInterval(recurrenceStrategy.RecurrenceTimeInterval).RepeatForever()).Build();

                return(trigger);
            }
            if (strategy is CronExpressionStrategy cronExpressionStrategy)
            {
                ITrigger trigger = TriggerBuilder.Create().WithCronSchedule(cronExpressionStrategy.CronExpression).Build();

                return(trigger);
            }

            throw new NotSupportedException("无当前类型执行策略!");
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Sets an ID to each rule. Generate name for unnamed instances.
 /// </summary>
 /// <param name="kpSystem"></param>
 private static void prepareKpSystem(KPsystem kpSystem)
 {
     foreach (var kpType in kpSystem.Types)
     {
         ExecutionStrategy kpES = kpType.ExecutionStrategy;
         while (kpES != null)
         {
             int id = 1;
             foreach (var kpRule in kpES.Rules)
             {
                 kpRule.Id = id;
                 id++;
             }
             kpES = kpES.Next;
         }
         //produce a name for unnamed instances
         int count = 0;
         foreach (var kpInstance in kpType.Instances)
         {
             if (String.IsNullOrWhiteSpace(kpInstance.Name))
             {
                 kpInstance.Name = "_" + kpType.Name.ToLower() + count;
                 count++;
             }
         }
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Determines how many child instances will eventually be generated after running all division rules. For each child
        /// instance, it generates KPChildInstance (sub class of MInstance) object and adds them as MInstance(regular
        /// instances) to MType. For each MInstance (including KPChildInstances) an SMV module will be generated.
        /// </summary>
        /// <param name="type">KP type (MType)</param>
        /// <returns>List of child instance of KPChildInstance type</returns>
        internal static List <KPChildInstance> generateKPChildInstances(MType type)
        {
            List <KPChildInstance> kpChildInstances = new List <KPChildInstance>();

            //After all divisions, how many child will be generated.
            int totalChildNumber = 1;
            ExecutionStrategy eS = type.ExecutionStrategy;

            while (eS != null)
            {
                foreach (var rule in eS.Rules)
                {
                    if (rule.Type == RuleType.MEMBRANE_DIVISION)
                    {
                        DivisionRule divisionRule = (DivisionRule)rule;
                        totalChildNumber *= divisionRule.Rhs.Count;
                    }
                }
                eS = eS.Next;
            }
            //for each parent instance, totalChildNumber, child instance will be generated
            foreach (MInstance kpInstance in type.Instances)
            {
                for (int childCount = 1; childCount <= totalChildNumber; childCount++)
                {
                    KPChildInstance kpChildInstance = new KPChildInstance(kpInstance);
                    kpChildInstance.Order = childCount;
                    kpChildInstance.Name  = kpInstance.Name + SMVPreFix.CHILD + childCount;
                    kpChildInstances.Add(kpChildInstance);
                }
            }
            return(kpChildInstances);
        }
Ejemplo n.º 19
0
 private void writeExecutionStrategy(ExecutionStrategy strategy)
 {
     owt.Write("{");
     if (strategy != null && !strategy.IsEmpty())
     {
         owt.Write("\"rules\":[");
         int i = 1;
         foreach (Rule rule in strategy.Rules)
         {
             writeRule(rule);
             if (i++ < strategy.Rules.Count)
             {
                 owt.Write(", ");
             }
         }
         owt.Write("]");
         owt.Write(", \"operator\":");
         writeStrategyOperator(strategy.Operator);
         if (strategy.Next != null)
         {
             owt.Write(", \"next\":");
             writeExecutionStrategy(strategy.Next);
         }
     }
     owt.Write("}");
 }
Ejemplo n.º 20
0
    ResolveFieldContext ResolveFieldContext(
        MyDataContext ctx,
        CancellationToken token,
        Document document,
        ISchema schema)
    {
        var operation        = document.Operations.FirstOrDefault();
        var variableValues   = ExecutionHelper.GetVariableValues(document, schema, operation?.Variables, null);
        var executionContext = new ExecutionContext
        {
            Document                  = document,
            Schema                    = schema,
            UserContext               = ctx,
            Variables                 = variableValues,
            Fragments                 = document.Fragments,
            CancellationToken         = token,
            Listeners                 = new IDocumentExecutionListener[0],
            Operation                 = operation,
            ThrowOnUnhandledException = true // DEBUG
        };

        var operationRootType = ExecutionHelper.GetOperationRootType(
            executionContext.Document,
            executionContext.Schema,
            executionContext.Operation);

        var node = ExecutionStrategy.BuildExecutionRootNode(executionContext, operationRootType);

        return(GetContext(executionContext, node.SubFields["companies"]));
    }
Ejemplo n.º 21
0
        public ArrayExecutionNode BuildEdgesArrayExecutionNode(ExecutionContext context, ExecutionNode node)
        {
            if (node is ObjectExecutionNode objectNode)
            {
                ExecutionStrategy.SetSubFieldNodes(context, objectNode);
                // Reference:
                // https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL/Execution/ExecutionStrategy.cs#L167

                var fields = CollectFields(context, objectNode.GraphType, node.Field.SelectionSet);
                if (fields.ContainsKey("edges"))
                {
                    var edgesField           = fields["edges"];
                    var schema               = context.Schema;
                    var edgesFieldDefinition = GetFieldDefinition(
                        context.Document, schema, objectNode.GetObjectGraphType(schema), edgesField);
                    var edgesNode = ExecutionStrategy.BuildExecutionNode(objectNode, edgesFieldDefinition.ResolvedType, edgesField, edgesFieldDefinition);
                    if (objectNode.Result is Connection <TNode> connection)
                    {
                        if (edgesNode is ArrayExecutionNode edgesArrayNode)
                        {
                            edgesArrayNode.Result = connection.Edges;
                            ExecutionStrategy.SetArrayItemNodes(context, edgesArrayNode);
                            return(edgesArrayNode);
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 22
0
        public async Task <ActivityResponse> ExecuteAsync(Activity activity, ActivityArgs activityArgs, CancellationToken cancellationToken)
        {
            var executionStrategy = ExecutionStrategy.CreateFor(_executeMethod);
            var parameters        = _executeMethod.BuildParametersFrom(activityArgs, cancellationToken);

            return(await executionStrategy.Execute(this, activity, parameters, activityArgs.TaskToken));
        }
Ejemplo n.º 23
0
 public ExecutionNode BuildExecutionNode(ExecutionNode node, IGraphType resolvedType, Field nodeField, FieldType fieldType)
 {
     return(ExecutionStrategy.BuildExecutionNode(
                node,
                resolvedType,
                nodeField,
                fieldType));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// 创建定时任务构造器
 /// </summary>
 /// <param name="strategy">执行策略</param>
 protected Crontab(ExecutionStrategy strategy)
 {
     //默认值
     this.Id = Guid.NewGuid().ToString();
     this.ExecutionStrategy = strategy;
     this.Status            = CrontabStatus.Pending;
     this.AddedTime         = DateTime.Now;
 }
Ejemplo n.º 25
0
        public StreamingModul(IndicatorCollection indicators, Strategy strategy, ExecutionStrategy execStrat, ITradingAPI tradingApi, string instrument)
        {
            this.indicators = indicators;
            this.strategy   = strategy;
            this.execStrat  = execStrat;
            this.tradingApi = tradingApi;

            this.instrument = instrument;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 调度任务
        /// </summary>
        /// <typeparam name="T">任务类型</typeparam>
        /// <param name="delay">延迟时间(毫秒)</param>
        /// <remarks>适用于没有参数,只有策略的任务</remarks>
        public static void Schedule <T>(int delay = 1000) where T : class, ICrontab
        {
            //调度任务
            Type crontabType = typeof(T);

            #region # 验证

            if (!CrontabSetting.CrontabStrategies.ContainsKey(crontabType.Name))
            {
                throw new InvalidOperationException($"没有为定时任务\"{crontabType.Name}\"配置执行策略");
            }

            #endregion

            ExecutionStrategy executionStrategy = CrontabSetting.CrontabStrategies[crontabType.Name];
            ICrontab          crontab           = CrontabFactory.CreateCrontab(crontabType, executionStrategy);

            IEnumerable <ICrontabExecutor> crontabExecutors = CrontabExecutorFactory.GetCrontabExecutorsFor(crontabType);
            foreach (ICrontabExecutor crontabExecutor in crontabExecutors)
            {
                JobKey jobKey = new JobKey(crontab.Id);
                if (!_Scheduler.CheckExists(jobKey).Result)
                {
                    Type       jobType    = crontabExecutor.GetType();
                    JobBuilder jobBuilder = JobBuilder.Create(jobType);

                    //设置任务数据
                    IDictionary <string, object> dictionary = new Dictionary <string, object>();
                    dictionary.Add(crontab.Id, crontab);
                    jobBuilder.SetJobData(new JobDataMap(dictionary));

                    //创建任务明细
                    IJobDetail jobDetail = jobBuilder.WithIdentity(jobKey).Build();

                    //创建触发器
                    ITrigger trigger = GetTrigger(crontab.ExecutionStrategy);

                    //为调度者添加任务明细与触发器
                    _Scheduler.ScheduleJob(jobDetail, trigger).Wait();

                    //开始调度
                    _Scheduler.StartDelayed(TimeSpan.FromMilliseconds(delay)).Wait();
                }
                else
                {
                    _Scheduler.ResumeJob(jobKey).Wait();
                }
            }

            //保存任务
            using (ICrontabStore crontabStore = ResolveMediator.ResolveOptional <ICrontabStore>())
            {
                crontab.Status = CrontabStatus.Scheduled;
                crontabStore?.Store(crontab);
            }
        }
        static void RunPatternBasedOnSelectedOption(string option)
        {
            switch (option)
            {
            case "1":
                ExecutionBuilderPattern.Run();
                break;

            case "2":
                ExecutionAbstractFactory.Run();
                break;

            case "3":
                ExecutionFactoryMethod.Run();
                break;

            case "4":
                ExecutionSingleton.Run();
                break;

            case "5":
                ExecutionAdapter.Run();
                break;

            case "6":
                ExecutionFacade.Run();
                break;

            case "7":
                ExecutionComposite.Run();
                break;

            case "8":
                ExecutionDecorator.Run();
                break;

            case "9":
                ExecutionCommand.Run();
                break;

            case "10":
                ExecutionStrategy.Run();
                break;

            case "11":
                ExecutionObserver.Run();
                break;

            case "12":
                ExecutionMediator.Run();
                break;

            default:
                throw new InvalidOperationException();
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// 静态构造器
 /// </summary>
 static CrontabSetting()
 {
     _CrontabLoginId    = FrameworkSection.Setting.CrontabAccountLoginId.Value;
     _CrontabPassword   = FrameworkSection.Setting.CrontabAccountPassword.Value;
     _CrontabStrategies = new ConcurrentDictionary <string, ExecutionStrategy>();
     foreach (CrontabStrategyElement element in FrameworkSection.Setting.CrontabStrategyElements)
     {
         ExecutionStrategy strategy = GetExecutionStrategy(element.StrategyType, element.Strategy);
         _CrontabStrategies.Add(element.Type, strategy);
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Receive an envelope for executing.
        /// </summary>
        internal override bool Receive(Envelope envelope)
        {
            ExecutionStrategy executionStrategy = _executionStrategy;

            if (executionStrategy != null)
            {
                executionStrategy.Execute(envelope);
            }

            RaiseEnvelopeReceivedEvent(envelope);
            return(true);
        }
Ejemplo n.º 30
0
    public ResolverStep(
        ExecutionStrategy strategy,
        IReadOnlyList <ISelection> selections)
    {
        if (selections is null)
        {
            throw new ArgumentNullException(nameof(selections));
        }

        Strategy    = strategy;
        _selections = selections.ToArray();
    }