Ejemplo n.º 1
0
        private WorkflowProcessor CreateWorkflowProcessor()
        {
            if (!string.IsNullOrEmpty(_path))
            {
                DirectoryInfo d = new DirectoryInfo(_path);

                var configurations = GetConfigurations(d, "workflow");

                var template = new TemplateRepository(_templateTypes)
                {
                    DefaultAction = TemplateModels.DefaultAction,
                };

                var metadatas = new MetadatRepository(_metadataTypes)
                {
                    DefaultAction = MetadataModels.DefaultAction.ToDictionary(c => c.Key, c => c.Value),
                };

                WorkflowProcessor processor = new WorkflowProcessor <TContext>(configurations, null)
                {
                    LoadExistingWorkflowsByExternalId = this.LoadExistingWorkflowsByExternalId,
                    OutputActions = CreateOutput,
                    Templates     = template,
                    Metadatas     = metadatas,
                    Services      = this.Services,
                };

                return(processor);
            }

            return(null);
        }
        public virtual WfResult Run(CancellationToken token)
        {
            WfResult result = WfResult.Unknown;

            //_logger.Write(String.Format("SqlServer: {0} query: {1}", _attributes[CONNECTION_STRING], _attributes[QUERY_STRING]));

            try
            {
                WorkflowAttributeCollection attributes = new WorkflowAttributeCollection();
                attributes.Add(PROCESSOR_NAME, _attributes[PROCESSOR_NAME]);
                attributes.Add(PROCESSOR_MODE_DEBUG, _attributes[PROCESSOR_MODE_DEBUG]);
                attributes.Add(PROCESSOR_MODE_VERBOSE, _attributes[PROCESSOR_MODE_VERBOSE]);
                attributes.Add(PROCESSOR_MODE_FORCESTART, _attributes[PROCESSOR_MODE_FORCESTART]);
                attributes.Add(WorkflowConstants.ATTRIBUTE_WORKFLOW_NAME, _attributes[WORKFLOW_NAME]);
                attributes.Add(CONNECTION_STRING, _attributes[CONNECTION_STRING]);
                attributes.Add(REQUEST_ID, _attributes[REQUEST_ID]);

                WorkflowProcessor wfp = new WorkflowProcessor(attributes);
                result = wfp.Run(token);
                _logger.Information("Activity finished with result {WfStatus}: {Message}", result.StatusCode, result.Message);
            }
            catch (SqlException ex)
            {
                throw ex;
                //_logger.Write(String.Format("SqlServer exception: {0}", ex.Message));
                //result = WfResult.Create(WfStatus.Failed, ex.Message, ex.ErrorCode);
            }
            return(result);
        }
Ejemplo n.º 3
0
        private void Consumer_Received(object sender, BasicDeliverEventArgs ea)
        {
            log.Debug($"Получено сообщение от {ea.RoutingKey}");
            Task.Run(() =>
            {
                var body                 = ea.Body;
                var props                = ea.BasicProperties;
                var replyProps           = channel.CreateBasicProperties();
                replyProps.CorrelationId = props.CorrelationId;

                try
                {
                    var message = Encoding.UTF8.GetString(body);
                    log.Debug($"Тело:\r\n{message}");
                    RabbitRequest rabbitRequest = JsonConvert.DeserializeObject <RabbitRequest>(message);

                    WorkflowProcessor processor = new WorkflowProcessor(rabbitRequest.MessageId, rabbitRequest.RequestCode);
                    processor.Run();

                    log.Debug($" [{QueueCode}] ({message})");
                    rabbitRequest.RequestCode++;
                }
                catch (Exception ex)
                {
                    log.Fatal($"[{QueueCode}] ({ex.Message})", ex);
                }
                finally
                {
                    if (CloseReason == null)
                    {
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                }
            });
        }
Ejemplo n.º 4
0
        public void SetupZeroActionsInWorkflowProcessorAndExecute()
        {
            var provider = Mock.Of <IServiceProvider>();
            var actions  = new List <ActionItem>()
            {
            };
            var workflowProcessor = new WorkflowProcessor <FakeWorkflowDataContent>(provider, actions);
            var context           = new FakeWorkflowDataContent();

            context.StringData = "0";

            context = workflowProcessor.Execute(context);
            Assert.Equal("0", context.StringData);
        }
        public void WFRun_Ok()
        {
            //var builder = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build();

            //string runnerName = builder.GetSection("Data:Runner").Value;
            //string connectionString = builder.GetSection("Data:Controller").Value;

            var    settings         = ConfigurationManager.AppSettings;
            string runnerName       = settings["Runner"];
            string connectionString = settings["Controller"];


            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.AppSettings()
                         //.ReadFrom.Configuration(builder)
                         .MinimumLevel.Debug()
                         //.WriteTo.File(path: @"c:\logs\log.txt",
                         //             rollOnFileSizeLimit: true,
                         //             rollingInterval: RollingInterval.Hour,
                         //             fileSizeLimitBytes: 1024000
                         //            )
                         .WriteTo.WorkflowLogger(connectionString: connectionString)
                         .CreateLogger();

            string WFName = "test107";

            WorkflowAttributeCollection attributes = new WorkflowAttributeCollection();

            //attributes.Add(WorkflowConstants.ATTRIBUTE_PROCESSOR_NAME, runnerName);
            attributes.Add(WorkflowConstants.ATTRIBUTE_DEBUG, "false");
            attributes.Add(WorkflowConstants.ATTRIBUTE_VERBOSE, "true");
            attributes.Add(WorkflowConstants.ATTRIBUTE_FORCESTART, "true");
            attributes.Add(WorkflowConstants.ATTRIBUTE_CONTROLLER_CONNECTIONSTRING, connectionString);
            attributes.Add(WorkflowConstants.ATTRIBUTE_WORKFLOW_NAME, WFName);
            //attributes.Add(WorkflowConstants.ATTRIBUTE_REQUEST_ID, Guid.NewGuid().ToString());


            WfResult wr = WfResult.Unknown;

            using (CancellationTokenSource cts = new CancellationTokenSource())
            {
                WorkflowProcessor wfp = new WorkflowProcessor(attributes);
                wr = wfp.Run(cts.Token);
            }

            Assert.IsTrue(wr.StatusCode == WfStatus.Succeeded);
        }
Ejemplo n.º 6
0
        public void SetupMultipleActionsInWorkflowProcessorAndExecuteInOrder()
        {
            var provider = Mock.Of <IServiceProvider>();
            var actions  = new List <ActionItem>()
            {
                new ActionItem(typeof(Action1)),
                new ActionItem(typeof(Action2)),
                new ActionItem(typeof(Action3)),
            };
            var workflowProcessor = new WorkflowProcessor <FakeWorkflowDataContent>(provider, actions);
            var context           = new FakeWorkflowDataContent();

            context.StringData = "0";

            context = workflowProcessor.Execute(context);
            Assert.Equal("0123", context.StringData);
        }
Ejemplo n.º 7
0
        private WorkflowEngine CreateEngine(MemoryStorage storage, string configText)
        {
            var template = new TemplateRepository(typeof(TemplateModels))
            {
                DefaultAction = TemplateModels.DefaultAction,
            };
            var metadatas = new MetadatRepository(typeof(MetadataModels))
            {
                DefaultAction = MetadataModels.DefaultAction.ToDictionary(c => c.Key, c => c.Value),
            };

            var serializer = new PartialJsonWorkflowSerializer();

            WorkflowsConfig configs = new WorkflowsConfig()
                                      .AddDocument(GetConfig(configText))
            ;

            var factory = new WorkflowFactory <RunContext>(null, null)
            {
                Serializer = serializer,
            };

            var processor = new WorkflowProcessor <RunContext>(configs, factory)
            {
                LoadExistingWorkflowsByExternalId = (key) => storage.GetBy <Workflow, string>(key, c => c.ExternalId).ToList(),
                OutputActions = () => CreateOutput(serializer, storage),
                Templates     = template,
                Metadatas     = metadatas,
            };

            WorkflowEngine engine = new WorkflowEngine()
            {
                Processor = processor,
            };

            return(engine);
        }
Ejemplo n.º 8
0
        public void InitializeWorkflowWithRule()
        {
            var config  = new WorkflowsConfig();
            var storage = new MemoryStorage();

            config.AddDocument(
                new WorkflowConfig()
            {
                Name = "wrk1", Label = "wrk1 config", Version = 1,
            }
                .AddInitializer(new InitializationOnEventConfig()
            {
                EventName = "evnt1",
            }.AddSwitch("State1"))
                .AddState(new StateConfig()
            {
                Name = "State1", Label = "State1",
            }
                          .AddEvent(new IncomingEventConfig()
            {
                Name = "evnt2"
            }
                                    .AddTransition(new TransitionConfig()
            {
                TargetStateName = "State2", WhenRule = (c) => c.IncomingEvent.Name == "evnt2"
            })
                                    )
                          )
                .AddState(new StateConfig()
            {
                Name = "State2", Label = "State2"
            }
                          )
                );

            var template = new TemplateRepository(typeof(TemplateModels))
            {
                DefaultAction = TemplateModels.DefaultAction,
            };
            var metadatas = new MetadatRepository(typeof(MetadataModels))
            {
                DefaultAction = MetadataModels.DefaultAction.ToDictionary(c => c.Key, c => c.Value),
            };

            var factory = new WorkflowFactory <RunContext>(null, null)
            {
                Serializer = new PartialJsonWorkflowSerializer()
            };

            var processor = new WorkflowProcessor <RunContext>(config, factory)
            {
                LoadExistingWorkflowsByExternalId = (key) => storage.GetBy <Workflow, string>(key, c => c.ExternalId).ToList(),
                OutputActions = () => CreateOutput(new PartialJsonWorkflowSerializer(), storage),
                Templates     = template,
                Metadatas     = metadatas,
            };


            var ev = new IncomingEvent()
            {
                Name         = "evnt1",
                Uuid         = Guid.NewGuid(),
                ExternalId   = Guid.NewGuid().ToString(),
                EventDate    = WorkflowClock.Now(),
                CreationDate = WorkflowClock.Now(),
            };

            processor.EvaluateEvent(ev);
            var wrk = storage.GetAll <Workflow>().FirstOrDefault(c => c.ExternalId == ev.ExternalId);

            Assert.AreEqual(wrk.CurrentState, "State1");


            ev = new IncomingEvent()
            {
                Name         = "evnt2",
                Uuid         = Guid.NewGuid(),
                ExternalId   = Guid.NewGuid().ToString(),
                EventDate    = WorkflowClock.Now(),
                CreationDate = WorkflowClock.Now(),
            };
            processor.EvaluateEvent(ev);
            wrk = storage.GetAll <Workflow>().FirstOrDefault(c => c.ExternalId == ev.ExternalId);
            Assert.AreEqual(wrk, null);
        }
Ejemplo n.º 9
0
        public void InitializeWorkflowWithPushedAction()
        {
            var config  = new WorkflowsConfig();
            var storage = new MemoryStorage();

            config.AddDocument(
                new WorkflowConfig()
            {
                Name = "wrk1", Label = "wrk1 config", Version = 1,
            }

                .AddInitializer(new InitializationOnEventConfig()
            {
                EventName = "evnt1", Recursive = true
            }.AddSwitch("State1"))

                .AddState(new StateConfig()
            {
                Name = "State1", Label = "State1",
            }
                          .AddIncomingActions(null, new ResultActionConfig()
            {
                Name = "act_on_state_in_1"
            })
                          .AddOutcomingActions(null, new ResultActionConfig()
            {
                Name = "act_on_state_out"
            })
                          .AddEvent(new IncomingEventConfig()
            {
                Name = "evnt1"
            }
                                    .AddAction(null, new ResultActionConfig()
            {
                Name = "act_on_event"
            })
                                    .AddTransition(new TransitionConfig()
            {
                TargetStateName = "State2"
            }
                                                   .AddAction(null, new ResultActionConfig()
            {
                Name = "act_on_transition"
            })
                                                   )

                                    )
                          )
                .AddState(new StateConfig()
            {
                Name = "State2", Label = "State2"
            }
                          .AddIncomingActions(null, new ResultActionConfig()
            {
                Name = "act_on_state_in_2"
            }
                                              .AddArgument("name", "@Event.Name")
                                              )

                          )
                );

            var template = new TemplateRepository(typeof(TemplateModels))
            {
                DefaultAction = TemplateModels.DefaultAction,
            };
            var metadatas = new MetadatRepository(typeof(MetadataModels))
            {
                DefaultAction = MetadataModels.DefaultAction.ToDictionary(c => c.Key, c => c.Value),
            };
            var factory = new WorkflowFactory <RunContext>(null, null)
            {
                Serializer = new PartialJsonWorkflowSerializer()
            };
            var processor = new WorkflowProcessor <RunContext>(config, factory)
            {
                LoadExistingWorkflowsByExternalId = (key) => storage.GetBy <Workflow, string>(key, c => c.ExternalId).ToList(),
                OutputActions = () => CreateOutput(new PartialJsonWorkflowSerializer(), storage),
                Templates     = template,
                Metadatas     = metadatas,
            };

            var ev = new IncomingEvent()
            {
                Name         = "evnt1",
                Uuid         = Guid.NewGuid(),
                ExternalId   = Guid.NewGuid().ToString(),
                EventDate    = WorkflowClock.Now(),
                CreationDate = WorkflowClock.Now(),
            };

            processor.EvaluateEvent(ev);
            var wrk = storage.GetAll <Workflow>().FirstOrDefault(c => c.ExternalId == ev.ExternalId);

            var act = wrk.LastEvent.Actions;

            act.First(c => c.Name == "act_on_state_in_1");
            act.First(c => c.Name == "act_on_state_out");
            act.First(c => c.Name == "act_on_event");
            act.First(c => c.Name == "act_on_transition");
        }
Ejemplo n.º 10
0
        static int Main(string[] args)
        {
            if (args.Length == 0 ||
                args.Contains(@"/help", StringComparer.InvariantCultureIgnoreCase))
            {
                help();
                return(0);
            }

            WorkflowAttributeCollection attributes = new WorkflowAttributeCollection();

            attributes.Add(WorkflowConstants.ATTRIBUTE_WORKFLOW_NAME, args[0].Replace("\"", ""));
            attributes.Add(WorkflowConstants.ATTRIBUTE_DEBUG, "false");
            attributes.Add(WorkflowConstants.ATTRIBUTE_VERBOSE, "false");
            attributes.Add(WorkflowConstants.ATTRIBUTE_FORCESTART, "false");

            var minLogLevel = LogEventLevel.Information;

            //bool debug = false;
            if (args.Contains(@"/D", StringComparer.InvariantCultureIgnoreCase))
            {
                attributes[WorkflowConstants.ATTRIBUTE_DEBUG] = "true";
                //debug = true;
                minLogLevel = LogEventLevel.Debug;
            }

            //bool forcestart = false;
            if (args.Contains(@"/R", StringComparer.InvariantCultureIgnoreCase))
            {
                attributes[WorkflowConstants.ATTRIBUTE_FORCESTART] = "true";
                //forcestart = true;
            }

            bool verbose = false;

            if (args.Contains(@"/V", StringComparer.InvariantCultureIgnoreCase))
            {
                attributes[WorkflowConstants.ATTRIBUTE_VERBOSE] = "true";
                verbose = true;
            }


            //var builder = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build();

            //string runnerName = builder.GetSection("Data:Runner").Value;
            //string connectionString = builder.GetSection("Data:Controller").Value;

            var    settings         = ConfigurationManager.AppSettings;
            string runnerName       = settings["Runner"];
            string connectionString = settings["Controller"];

            attributes.Add(WorkflowConstants.ATTRIBUTE_CONTROLLER_CONNECTIONSTRING, connectionString);


            //string runnerName = settings["Runner"];
            if (String.IsNullOrEmpty(runnerName))
            {
                runnerName = "Default";
            }

            attributes.Add(WorkflowConstants.ATTRIBUTE_PROCESSOR_NAME, runnerName);


            if (verbose)
            {
                Log.Logger = new LoggerConfiguration()
                             //.ReadFrom.Configuration(builder)
                             .ReadFrom.AppSettings()
                             .MinimumLevel.Is(minLogLevel)
                             //.WriteTo.Console()
                             .WriteTo.WorkflowLogger(connectionString: connectionString)
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.Is(minLogLevel)
                             .WriteTo.WorkflowLogger(connectionString: connectionString)
                             .CreateLogger();
            }

            try
            {
                WfResult wr = WfResult.Unknown;
                using (CancellationTokenSource cts = new CancellationTokenSource())
                {
                    WorkflowProcessor wfp = new WorkflowProcessor(attributes);
                    wr = wfp.Run(cts.Token);
                }

                if (wr.StatusCode != WfStatus.Succeeded)
                {
                    return(1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error: {0}, {1}", ex.HResult, ex.Message));
                return(1);
            }
            return(0);
        }