public void UnserializeEventIncoming() { string payload = @"{ 'Name': 'evnt1', 'Uuid': '352d5082-3fb9-4db8-8a59-bc864ade4929', 'ExternalId': 'c65ea000-dce0-44a3-a6f3-9daf7eebaefe', 'CreationDate': '2019-09-23T09:48:52.1868472+02:00', 'EventDate': '2019-09-23T09:48:47.3047926+02:00', 'Site': 'site1', 'infos': { 'name': 'toto' }, 'infos2': [ { 'name': 'toto' }, { 'name': 'titi' } ] }".Replace("'", "\""); IWorkflowSerializer serializer = new PartialJsonWorkflowSerializer(); var msg = new IncomingEvent(); serializer.Populate(msg, payload); var payload2 = serializer.Serialize(msg); msg = new IncomingEvent(); serializer.Populate(msg, payload2); var payload3 = serializer.Serialize(msg); Assert.AreEqual(payload2, payload3); }
public void TestGenericEvents() { var a = new EventSource(); var e = new IncomingEvent<EventArgs> { Channel = "a", DataObject = new EventArgs { Id = 10 }, EventName = "foo" }; (e as IncomingEvent).Data = "{id:10}"; var events = new List<IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.GetEventSubscription<EventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.DataObject.Id, e.DataObject.Id); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 2, "Event should get through twice when you have two subscriptions"); }
// ExecuteDetails can continue in child class /// <summary> /// /// </summary> /// <param name="env"></param> /// <param name="messageTypes"> the expected type to receive from the request </param> /// <returns></returns> protected Envelope DoReliableRequestReply(Envelope env, Type[] messageTypes) { Logger.Debug($"{this.GetType().Name}-{this.ConversationId}, Sending Envelope with message Type {env.Message.GetType()}"); SubSystem.outQueue.Enqueue(env); //Start timeout for message. int maxAttemps = 25; int attempts = 1; while (!IncomingEvent.WaitOne(1000) && attempts < maxAttemps) { Logger.Debug($"{this.GetType().Name}-{this.ConversationId}, Sending Envelope with message Type {env.Message.GetType()} - Retry number {attempts}"); SubSystem.outQueue.Enqueue(env); attempts++; } Envelope receivedEnv = null; if (IncomingEnvelopes.TryDequeue(out receivedEnv)) { if (!messageTypes.Contains(receivedEnv.Message.GetType())) { //We recieved the wrong message, or message we not in queue. Logger.DebugFormat("{0}-{1}, Recieved wrong message.", this.GetType().Name, this.ConversationId); receivedEnv = null; //Makes sure failure is null. this.State = PossibleState.Failed; } } else { Logger.DebugFormat("{0}-{1}, Didn't receive a message in Request Reply.", this.GetType().Name, this.ConversationId); } return(receivedEnv); //Returns null on a failure. }
public string ProcessMessage(string message, ChatHistory chat) { try { var parsedTime = DateTime.ParseExact(message, "HH:mm", System.Globalization.CultureInfo.InvariantCulture); int minutesMultiplier = 60; DateTime eventDate = chat.EventDate.AddMinutes(parsedTime.Hour * minutesMultiplier + parsedTime.Minute); if (eventDate < DateTime.Now.Date) { return(Resource.ResponseMessages.TIME_SMALLER_THAN_NOW); } var eventToAdd = new IncomingEvent() { ChatId = chat.Id, Description = chat.Description, InvocationTime = eventDate }; this.eventStorageService.AddEventToStore(eventToAdd); this.chatStorageService.RemoveChat(chat); return(Resource.ResponseMessages.TIME_RESPONSE_MESSAGE); } catch (Exception) { return(Resource.ResponseMessages.TIME_CANNOT_PARSE); } }
private void PostOnStateMachine(IncomingEvent incomingEvent, StdEnum stateMachineEnum) { foreach (var engineAgent in GetEngineAgents(stateMachineEnum)) { Agent.Post(engineAgent, incomingEvent); } }
public void TestGenericEvents() { var a = new EventSource(); var e = new IncomingEvent <EventArgs> { Channel = "a", DataObject = new EventArgs { Id = 10 }, EventName = "foo" }; (e as IncomingEvent).Data = "{id:10}"; var events = new List <IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.GetEventSubscription <EventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.DataObject.Id, e.DataObject.Id); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 2, "Event should get through twice when you have two subscriptions"); }
private static RunContext CreateContextForEvaluateArgument() { var factory = new WorkflowFactory <RunContext>(null, null) { Serializer = new PartialJsonWorkflowSerializer() }; var ev = new IncomingEvent() { Name = "evnt1", Uuid = Guid.NewGuid(), ExternalId = Guid.NewGuid().ToString(), EventDate = WorkflowClock.Now(), CreationDate = WorkflowClock.Now(), }; var wrk = factory.CreateNewWorkflow( "Test", 1, ev.ExternalId, new DynObject() ); RunContext ctx = new RunContext().Set(wrk, ev, factory); return(ctx); }
/// <summary> /// Queues to cache. This method is non-blocking, use SaveToCache for a blocking method. /// </summary> public static void QueueToCache(byte[] fileData) { if (SettingsSystem.CurrentSettings.EnableCache) { IncomingQueue.Enqueue(fileData); IncomingEvent.Set(); } }
internal bool EvaluateFilter(IncomingEvent @event) { if (_evaluateFilter == null) { BuildWorkflow(); } RunContext ctx = new RunContext().Set(null, @event, null); return(_evaluateFilter(ctx)); }
/// <summary> /// Processes the queued objects and save them as files in async mode /// </summary> private static void ProcessingThreadMain() { while (!_stop) { if (IncomingQueue.TryDequeue(out var incomingBytes)) { SaveToCache(incomingBytes); } else { IncomingEvent.WaitOne(500); } } }
/// <summary> /// Processes the queued objects and save them as files in async mode /// </summary> private static void ProcessingThreadMain() { while (!_stop && SettingsSystem.CurrentSettings.EnableCache) { if (IncomingQueue.TryDequeue(out var incomingBytes)) { SaveToCache(incomingBytes); } else { IncomingEvent.WaitOne(500); } } }
private void ProcessingThreadMain() { while (true) { byte[] incomingBytes; if (IncomingQueue.TryDequeue(out incomingBytes)) { SaveToCache(incomingBytes); } else { IncomingEvent.WaitOne(500); } } }
public void TestEventsAreTriggered() { var a = new EventSource(); var e = new IncomingEvent {Channel = "a", Data = "{}", EventName = "foo"}; var events = new List<IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 1); }
public async Task TestEventContractAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() }); pusher.AddContract(EventContract.Create <FakeEvent>("fooHappened")); await pusher.ConnectAsync(); var sentEvent = new IncomingEvent <FakeEvent> { Channel = "foo", DataObject = new FakeEvent { Id = 1, Text = "foo" }, EventName = "fooHappened" }; var channel = await pusher.SubscribeToChannelAsync("foo"); var eventsReceived = 0; channel.GetEventSubscription <FakeEvent>().EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.DataObject.Id, receivedEvent.DataObject.Id); Assert.AreEqual(sentEvent.DataObject.Text, receivedEvent.DataObject.Text); Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; }; channel.EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; Assert.AreEqual(typeof(IncomingEvent <FakeEvent>), receivedEvent.GetType()); }; factory.LastCreated.SendData(JsonConvert.SerializeObject(sentEvent)); Assert.AreEqual(2, eventsReceived); }
public void TestEventsAreTriggered() { var a = new EventSource(); var e = new IncomingEvent { Channel = "a", Data = "{}", EventName = "foo" }; var events = new List <IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 1); }
public IEnumerable <WorkflowConfig> Get(IncomingEvent @event) { if (this._configs.Count == 0) { Trace.WriteLine(new { Message = "no state configuration loaded" }); } foreach (WorkflowConfig config in this._subConfigs) { if (config.EvaluateFilter(@event)) { yield return(config); } } if (this._subConfigs.Count == 0) { Trace.WriteLine(new { Message = "no state configuration loaded" }); } }
private Prediction CreatePrediction(IncomingEvent incomingEvent) { Prediction prediction = new Prediction(); prediction.IncomingEventId = incomingEvent.Id; foreach (TeamInfo teamInfo in incomingEvent.TeamsInfo) { if (teamInfo.IsHomeGame) { prediction.HomeTeamId = teamInfo.TeamId; } else { prediction.AwayTeamId = teamInfo.TeamId; } } return(prediction); }
private void PredictEvent(IncomingEvent incomingEvent) { try { TeamData homeTeam = null; TeamData awayTeam = null; Prediction prediction = this.CreatePrediction(incomingEvent); int maxScore = SettingsReader.GetInstance().ReadMaxScore(incomingEvent.SportType); foreach (TeamInfo teamInfo in incomingEvent.TeamsInfo) { if (teamInfo.IsHomeGame) { homeTeam = new TeamData(teamInfo.TeamEvents, true); } else { awayTeam = new TeamData(teamInfo.TeamEvents, false); } } Predictor predictor = new Predictor(homeTeam, awayTeam, maxScore); predictor.CalcProbabilities(); prediction.HomeWinProbability = predictor.HomeWinProbability; prediction.DrawProbability = predictor.DrawProbability; prediction.AwayWinProbability = predictor.AwayWinProbability; this.AddNewPrediction(prediction); } catch (Exception ex) { Log.Error("Exception while trying to PredictEvent", ex); } }
public void GetConfigEventIncoming() { var config = new WorkflowsConfig(); config.AddDocument(new WorkflowConfig() { Name = "wrk1", Label = "wrk1 config", Version = 1, } .AddFilter("Country", "France") ); config.AddDocument(new WorkflowConfig() { Name = "wrk2", Label = "wrk2 config", Version = 1, } .AddFilter("Country", "Germany") ); var ev = new IncomingEvent() { Name = "evnt1", Uuid = Guid.NewGuid(), ExternalId = Guid.NewGuid().ToString(), EventDate = DateTimeOffset.Now, CreationDate = DateTimeOffset.Now, } .AddExtendedDatas("Country", "Germany"); var item = config.Get(ev).First(); Assert.AreEqual(item.Name, "wrk2"); }
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"); }
public void Send(Context context, XComponent.Trade.UserObject.Trade evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.Trade.UserObject.Trade(), IncomingEventType.Transition, HeaderFactory.Create(context, 13, privateTopic)); Agent.Post(_engineAgentsById[context.AgentId], incomingEvent); }
public void SendEvent(StdEnum stateMachineEnum, XComponent.Order.UserObject.OrderCreation evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.Order.UserObject.OrderCreation(), IncomingEventType.Transition, HeaderFactory.Create(10, (int)stateMachineEnum, -729436854, privateTopic)); PostOnStateMachine(incomingEvent, stateMachineEnum); }
public void SendEvent(StdEnum stateMachineEnum, XComponent.Common.Event.DefaultEvent evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.Common.Event.DefaultEvent(), IncomingEventType.Transition, HeaderFactory.Create(6, (int)stateMachineEnum, -729436854, privateTopic)); PostOnStateMachine(incomingEvent, stateMachineEnum); }
public async Task TestEventContractAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() }); pusher.AddContract(EventContract.Create<FakeEvent>("fooHappened")); await pusher.ConnectAsync(); var sentEvent = new IncomingEvent<FakeEvent> { Channel = "foo", DataObject = new FakeEvent {Id = 1, Text = "foo"}, EventName = "fooHappened" }; var channel = await pusher.SubscribeToChannelAsync("foo"); var eventsReceived = 0; channel.GetEventSubscription<FakeEvent>().EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.DataObject.Id, receivedEvent.DataObject.Id); Assert.AreEqual(sentEvent.DataObject.Text, receivedEvent.DataObject.Text); Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; }; channel.EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; Assert.AreEqual(typeof(IncomingEvent<FakeEvent>), receivedEvent.GetType()); }; factory.LastCreated.SendData(JsonConvert.SerializeObject(sentEvent)); Assert.AreEqual(2, eventsReceived); }
public void SendEvent(StdEnum stateMachineEnum, XComponent.Referential.UserObject.Instrument evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.Referential.UserObject.Instrument(), IncomingEventType.Transition, HeaderFactory.Create(9, (int)stateMachineEnum, 1667656897, privateTopic)); PostOnStateMachine(incomingEvent, stateMachineEnum); }
public void SendEvent(StdEnum stateMachineEnum, XComponent.Authentication.UserObject.InitializationSuccess evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.Authentication.UserObject.InitializationSuccess(), IncomingEventType.Transition, HeaderFactory.Create(7, (int)stateMachineEnum, 769565298, privateTopic)); PostOnStateMachine(incomingEvent, stateMachineEnum); }
public void SendEvent(StdEnum stateMachineEnum, XComponent.HelloWorld.UserObject.SayHello evt, string privateTopic = null) { var incomingEvent = new IncomingEvent(evt != null ? evt : new XComponent.HelloWorld.UserObject.SayHello(), IncomingEventType.Transition, HeaderFactory.Create(9, (int)stateMachineEnum, -69981087, privateTopic)); PostOnStateMachine(incomingEvent, stateMachineEnum); }
public abstract RunContext CreateBaseContext(Workflow workflow, IncomingEvent incomingEvent);
public abstract Event CreateBaseEvent(IncomingEvent incomingEvent);
public void AddEventToStore(IncomingEvent incomingEvent) { incomingEvent.Id = this.redisClient.GetNextSequence(); var store = this.redisClient.Store(incomingEvent); }
public void RemoveEvent(IncomingEvent incomingEvent) { this.redisClient.DeleteById(incomingEvent.ChatId); }
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); }
public void OnRoomCreated(IncomingEvent incomingEvent) { // Do whatever you want with incoming event (persist or process) }