public SentimentAnalysis(StreamRecord record) { UserId = record.Keys["UserID"].S; Type = "text"; Data = record.NewImage["Content"].S; SentimentLevel = "medium"; }
static public bool SendDataViaSerial(int serialID, List <byte> dataValue) { bool retValue = false; try { if (serialList[serialID] == null || !serialList[serialID].IsOpen) { retValue = false; return(retValue); } while (serialList[serialID].BytesToWrite + dataValue.Count > serialList[serialID].WriteBufferSize) { } ; serialList[serialID].Write(dataValue.ToArray(), 0, dataValue.Count); if (serialID == 0) { boardSentStream = ByteToHexStr(dataValue); StreamRecord.InsertSentStream(boardSentStream); } while (serialList[serialID].BytesToWrite > 0) { } ; retValue = true; } catch (Exception) { }; return(retValue); }
public virtual void ProcessElement(StreamRecord <T> record) { var element = record.Value; var newTimestamp = UserFunction.ExtractTimestamp(element, record.HasTimestamp ? record.Timestamp : long.MinValue); Output.Collect(record.Replace(record.Value, newTimestamp)); }
static public void BoardSerialEvent(string dataStream) { boardSerialStream += dataStream; if ((int)boardSerialStream[boardSerialStream.Length - 1] != BoardsManager.boardInfo.COMM_END_SYMBOL) { dealWithBoardSerialStream = false; return; } dealWithBoardSerialStream = true; int streamStartPoint = -1; int streamEndPoint = boardSerialStream.Length - 1; for (int i = streamEndPoint; i >= 0; i--) { if ((int)boardSerialStream[i] == BoardsManager.boardInfo.COMM_START_SYMBOL) { streamStartPoint = i; break; } } if (streamStartPoint == -1) { boardSerialStream = string.Empty; dealWithBoardSerialStream = false; return; } boardSerialStream = boardSerialStream.Substring(streamStartPoint, streamEndPoint - streamStartPoint + 1); StreamRecord.InsertRecievedStream(ByteToHexStr(boardSerialStream)); BoardSerialStreamDoEvents(boardSerialStream); boardSerialStream = string.Empty; dealWithBoardSerialStream = false; }
static public bool SendDataViaSerial(int serialID, byte dataValue) { bool retValue = false; try { if (serialList[serialID] == null || !serialList[serialID].IsOpen) { retValue = false; return(retValue); } while (serialList[serialID].BytesToWrite + 1 > serialList[serialID].WriteBufferSize) { } ; List <byte> dataValueByteArray = new List <byte>(); dataValueByteArray.Clear(); dataValueByteArray.Add(dataValue); serialList[serialID].Write(dataValueByteArray.ToArray(), 0, 1); if (serialID == 0) { boardSentStream = ByteToHexStr(dataValueByteArray); StreamRecord.InsertSentStream(boardSentStream); } while (serialList[serialID].BytesToWrite > 0) { } ; retValue = true; } catch (Exception) { }; return(retValue); }
private string SerializeStreamRecord(StreamRecord streamRecord) { using (var writer = new StringWriter()) { _jsonSerializer.Serialize(writer, streamRecord); return(writer.ToString()); } }
private DomainEventStream ConvertFrom(StreamRecord record) { return(new DomainEventStream( record.CommandId, record.AggregateRootId, record.AggregateRootTypeName, record.CreatedOn, _eventSerializer.Deserialize <IDomainEvent>(_jsonSerializer.Deserialize <IDictionary <string, string> >(record.Events)))); }
private DomainEventStream ConvertFrom(StreamRecord record) { return(new DomainEventStream( record.CommandId, record.AggregateRootId, record.AggregateRootTypeCode, record.Version, record.Timestamp, _eventSerializer.Deserialize <IDomainEvent>(_jsonSerializer.Deserialize <IDictionary <int, string> >(record.Events)))); }
public void Collect <T>(OutputTag <T> outputTag, StreamRecord <T> record) { if (_outputTag == null || !_outputTag.Equals(outputTag)) { // we are not responsible for emitting to the side-output specified by this OutputTag. return; } PushToRecordWriter(record); }
public void Collect(StreamRecord <TOutput> record) { if (_outputTag != null) { // we are not responsible for emitting to the main output. return; } PushToRecordWriter(record); }
private void PushToRecordWriter <T>(StreamRecord <T> record) { _serializationDelegate.Instance = record; try { _recordWriter.Emit(_serializationDelegate); } catch (Exception e) { throw new RuntimeException(e.Message, e); } }
public virtual void ProcessElement(StreamRecord <TElement> record) { var element = record.Value; var newTimestamp = UserFunction.ExtractTimestamp(element, record.HasTimestamp ? record.Timestamp : long.MinValue); Output.Collect(record.Replace(record.Value, newTimestamp)); var nextWatermark = UserFunction.CheckAndGetNextWatermark(element, newTimestamp); if (nextWatermark != null && nextWatermark.Timestamp > _currentWatermark) { _currentWatermark = nextWatermark.Timestamp; Output.EmitWatermark(nextWatermark); } }
static public bool ResetSerial() { bool retValue = false; try { serialByControlObject.Clear(); foreach (SerialPort serialPort in serialList) { try { serialPort.Close(); } catch (Exception) { }; } StreamRecord.Clear(); serialList.Clear(); serialCount = 1; retValue = true; } catch (Exception) { }; return(retValue); }
/// <summary> /// Creates a new <see cref="TimestampedCollector{TElement}"/> that wraps the given <see cref="IOutput{TElement}"/>. /// </summary> /// <param name="output"></param> public TimestampedCollector(IOutput <StreamRecord <TElement> > output) { _output = output; _reuse = new StreamRecord <TElement>(default);
public void SetKeyContextElement2 <T>(StreamRecord <T> record) { throw new NotImplementedException(); }
public void ProcessElement(StreamRecord <TInput> element) { throw new System.NotImplementedException(); }
public override TryHandleRecordResult Execute( StandardTryHandleRecordOp operation) { operation.MustForArg(nameof(operation)).NotBeNull(); var sqlServerLocator = this.TryGetLocator(operation); var convertedRecordFilter = this.ConvertRecordFilter(operation.RecordFilter, sqlServerLocator); var tagIdsForEntryCsv = this.GetIdsAddIfNecessaryTag( sqlServerLocator, operation.Tags ?? new List <NamedValue <string> >()) .Select(_ => _.ToStringInvariantPreferred()) .ToCsv(); var storedProcOp = StreamSchema.Sprocs.TryHandleRecord.BuildExecuteStoredProcedureOp( this.Name, operation.Concern, operation.Details ?? Invariant($"Created by {nameof(StandardTryHandleRecordOp)}."), convertedRecordFilter, tagIdsForEntryCsv, operation.OrderRecordsBy, operation.MinimumInternalRecordId, operation.InheritRecordTags, operation.StreamRecordItemsToInclude); var sqlProtocol = this.BuildSqlOperationsProtocol(sqlServerLocator); var sprocResult = sqlProtocol.Execute(storedProcOp); int shouldHandle = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ShouldHandle)].GetValueOfType <int>(); int isBlocked = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.IsBlocked)].GetValueOfType <int>(); if (shouldHandle != 1) { return(new TryHandleRecordResult(null, isBlocked == 1)); } long internalRecordId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.InternalRecordId)].GetValueOfType <long>(); int serializerRepresentationId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.SerializerRepresentationId)].GetValueOfType <int>(); int identifierTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.IdentifierTypeWithVersionId)].GetValueOfType <int>(); int objectTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ObjectTypeWithVersionId)].GetValueOfType <int>(); string stringSerializedId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.StringSerializedId)].GetValueOfType <string>(); string stringSerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.StringSerializedObject)].GetValueOfType <string>(); byte[] binarySerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.BinarySerializedObject)].GetValueOfType <byte[]>(); DateTime recordTimestampRaw = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.RecordDateTime)].GetValueOfType <DateTime>(); DateTime?objectTimestampRaw = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.ObjectDateTime)].GetValueOfType <DateTime?>(); string recordTagIdsCsv = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.TryHandleRecord.OutputParamName.TagIdsCsv)].GetValueOfType <string>(); var identifiedSerializerRepresentation = this.GetSerializerRepresentationFromId(sqlServerLocator, serializerRepresentationId); var identifierType = this.GetTypeById(sqlServerLocator, identifierTypeWithVersionId, true); var objectType = this.GetTypeById(sqlServerLocator, objectTypeWithVersionId, true); var tagIds = recordTagIdsCsv?.FromCsv().Select(_ => long.Parse(_, CultureInfo.InvariantCulture)).ToList(); var tags = tagIds == null ? null : this.GetTagsByIds(sqlServerLocator, tagIds); var recordTimestamp = recordTimestampRaw.ToUtc(); var objectTimestamp = objectTimestampRaw == null ? (DateTime?)null : objectTimestampRaw.ToUtc(); var metadata = new StreamRecordMetadata( stringSerializedId, identifiedSerializerRepresentation.SerializerRepresentation, identifierType, objectType, tags, recordTimestamp, objectTimestamp); DescribedSerializationBase payload; if (operation.StreamRecordItemsToInclude == StreamRecordItemsToInclude.MetadataAndPayload) { switch (identifiedSerializerRepresentation.SerializationFormat) { case SerializationFormat.Binary: payload = new BinaryDescribedSerialization( objectType.WithVersion, identifiedSerializerRepresentation.SerializerRepresentation, binarySerializedObject); break; case SerializationFormat.String: payload = new StringDescribedSerialization( objectType.WithVersion, identifiedSerializerRepresentation.SerializerRepresentation, stringSerializedObject); break; default: throw new NotSupportedException( Invariant($"{nameof(SerializationFormat)} {identifiedSerializerRepresentation.SerializationFormat} is not supported.")); } } else { payload = new NullDescribedSerialization(metadata.TypeRepresentationOfObject.WithVersion, metadata.SerializerRepresentation); } var record = new StreamRecord(internalRecordId, metadata, payload); var result = new TryHandleRecordResult(record); return(result); }
public static Domain.Notification Parse(StreamRecord record) { var notificationSend = new Dynamo.NotificationRepository().Parse(record.NewImage); return(Parse(notificationSend)); }
private DomainEventStream ConvertFrom(StreamRecord record) { return new DomainEventStream( record.CommandId, record.AggregateRootId, record.AggregateRootTypeName, record.Version, record.CreatedOn, _eventSerializer.Deserialize<IDomainEvent>(_jsonSerializer.Deserialize<IDictionary<string, string>>(record.Events))); }
public WindowTriggerResult OnElement(StreamRecord <TInput> element) { return(Trigger.OnElement(element.Value, element.Timestamp, Window, this)); }
public override StreamRecord Execute( StandardGetLatestRecordOp operation) { operation.MustForArg(nameof(operation)).NotBeNull(); var sqlServerLocator = this.TryGetLocator(operation); var convertedRecordFilter = this.ConvertRecordFilter(operation.RecordFilter, sqlServerLocator); var storedProcOp = StreamSchema.Sprocs.GetLatestRecord.BuildExecuteStoredProcedureOp( this.Name, convertedRecordFilter, operation.StreamRecordItemsToInclude); var sqlProtocol = this.BuildSqlOperationsProtocol(sqlServerLocator); var sprocResult = sqlProtocol.Execute(storedProcOp); long internalRecordId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.InternalRecordId)].GetValueOfType <long>(); if (internalRecordId == StreamSchema.Tables.Record.NullId) { switch (operation.RecordNotFoundStrategy) { case RecordNotFoundStrategy.ReturnDefault: return(null); case RecordNotFoundStrategy.Throw: throw new InvalidOperationException( Invariant( $"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'.")); default: throw new NotSupportedException( Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported.")); } } int serializerRepresentationId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.SerializerRepresentationId)].GetValueOfType <int>(); int identifierTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.IdentifierTypeWithVersionId)].GetValueOfType <int>(); int objectTypeWithVersionId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.ObjectTypeWithVersionId)].GetValueOfType <int>(); string stringSerializedId = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.StringSerializedId)].GetValueOfType <string>(); string stringSerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.StringSerializedObject)].GetValueOfType <string>(); byte[] binarySerializedObject = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.BinarySerializedObject)].GetValueOfType <byte[]>(); DateTime recordTimestampRaw = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.RecordDateTime)].GetValueOfType <DateTime>(); DateTime?objectTimestampRaw = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.ObjectDateTime)].GetValueOfType <DateTime?>(); string tagIdsCsv = sprocResult.OutputParameters[nameof(StreamSchema.Sprocs.GetLatestRecord.OutputParamName.TagIdsCsv)].GetValueOfType <string>(); var identifiedSerializerRepresentation = this.GetSerializerRepresentationFromId(sqlServerLocator, serializerRepresentationId); var identifierType = this.GetTypeById(sqlServerLocator, identifierTypeWithVersionId, true); var objectType = this.GetTypeById(sqlServerLocator, objectTypeWithVersionId, true); var tagIds = tagIdsCsv?.FromCsv().Select(_ => long.Parse(_, CultureInfo.InvariantCulture)).ToList(); var tags = tagIds == null ? null : this.GetTagsByIds(sqlServerLocator, tagIds); var recordTimestamp = recordTimestampRaw.ToUtc(); var objectTimestamp = objectTimestampRaw == null ? (DateTime?)null : objectTimestampRaw.ToUtc(); var metadata = new StreamRecordMetadata( stringSerializedId, identifiedSerializerRepresentation.SerializerRepresentation, identifierType, objectType, tags, recordTimestamp, objectTimestamp); DescribedSerializationBase payload; if (operation.StreamRecordItemsToInclude == StreamRecordItemsToInclude.MetadataAndPayload) { switch (identifiedSerializerRepresentation.SerializationFormat) { case SerializationFormat.Binary: payload = new BinaryDescribedSerialization( objectType.WithVersion, identifiedSerializerRepresentation.SerializerRepresentation, binarySerializedObject); break; case SerializationFormat.String: payload = new StringDescribedSerialization( objectType.WithVersion, identifiedSerializerRepresentation.SerializerRepresentation, stringSerializedObject); break; default: throw new NotSupportedException( Invariant($"{nameof(SerializationFormat)} {identifiedSerializerRepresentation.SerializationFormat} is not supported.")); } } else { payload = new NullDescribedSerialization(metadata.TypeRepresentationOfObject.WithVersion, metadata.SerializerRepresentation); } var result = new StreamRecord(internalRecordId, metadata, payload); return(result); }
// Out of scope for MVP release // Since the stream messages number could be large depending on the script the operation uses pagination. // There are two query parameters limit and start which can be used to move through the stream records list. Record at index 0 is the last registered stream records. Moving up increasing the start of the stream records moves you back in the history of stream records. // <param name="limit">Maximum number of records to be retrieved</param> // <param name="start">Position in the history of records where the records retrieval is requested from.</param> // public ActionResult<StreamRecord[]> Get([FromRoute] string id, [FromRoute(Name ="stream-type")] StreamType streamType, [FromQuery] int limit = 20, [FromQuery] int start = 0) { public ActionResult <StreamRecord[]> Get([FromRoute] string id, [FromRoute(Name = "stream-type")] StreamType streamType) { ActionResult <StreamRecord[]> result = null; IScriptExecutionDataStreams scriptResult = null; // Get Script Execution from ScriptExecutionMediator try { var authzToken = SessionToken.FromHeaders(Request.Headers); scriptResult = ScriptExecutionMediatorSingleton. Instance. ScriptExecutionMediator. GetScriptExecutionDataStreams(authzToken.UserName, id); if (scriptResult != null) { switch (streamType) { case StreamType.debug: result = Ok( StreamRecord.FromStreamRecords(scriptResult.Streams.Debug)); break; case StreamType.error: result = Ok( StreamRecord.FromStreamRecords(scriptResult.Streams.Error)); break; case StreamType.information: result = Ok( StreamRecord.FromStreamRecords(scriptResult.Streams.Information)); break; case StreamType.verbose: result = Ok( StreamRecord.FromStreamRecords(scriptResult.Streams.Verbose)); break; case StreamType.warning: result = Ok( StreamRecord.FromStreamRecords(scriptResult.Streams.Warning)); break; } } else { result = NotFound( new ErrorDetails( ApiErrorCodes.GetErrorCode( nameof(APIGatewayResources.ScriptsController_ScriptNotFound)), string.Format(APIGatewayResources.ScriptsController_ScriptNotFound, id))); } } catch (RunspaceEndpointException runspaceEndointException) { result = StatusCode( runspaceEndointException.HttpErrorCode, new ErrorDetails( ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode), runspaceEndointException.Message, runspaceEndointException.ToString())); } catch (Exception exc) { result = StatusCode( 500, new ErrorDetails( ApiErrorCodes.GetErrorCode( nameof(APIGatewayResources.ScriptStreamsController_ScriptStorageService_FailedToRetrieveScriptStreams)), APIGatewayResources.ScriptStreamsController_ScriptStorageService_FailedToRetrieveScriptStreams, exc.ToString())); } return(result); }
public Notification Parse(StreamRecord record) { var notification = new Notification { IdNotification = record.Keys["IdNotification"].S }; foreach (var field in record.NewImage) { if (field.Key == "IdTemplate") { notification.IdTemplate = int.Parse(field.Value.N); } if (field.Key == "CreationDate") { notification.CreationDate = DateTime.Parse(field.Value.S); } if (field.Key == "Timer") { notification.Timer = int.Parse(field.Value.N); } if (field.Key == "NextTime") { notification.NextTime = DateTime.Parse(field.Value.S); } if (field.Key == "Path") { notification.Path = field.Value.S; } if (field.Key == "Reminder") { notification.Reminder = field.Value.N == "1" ? true : false; } if (field.Key == "IdNotification") { notification.IdNotification = field.Value.S; } if (field.Key == "Fields") { notification.Fields = field.Value.S; } if (field.Key == "Mail") { notification.Mail = field.Value.S; } if (field.Key == "ModifyDate") { notification.ModifyDate = DateTime.Parse(field.Value.S); } if (field.Key == "End") { notification.End = DateTime.Parse(field.Value.S); } if (field.Key == "State") { notification.State = int.Parse(field.Value.N); } if (field.Key == "Begin") { notification.Begin = DateTime.Parse(field.Value.S); } if (field.Key == "Origin") { notification.Origin = int.Parse(field.Value.N); } if (field.Key == "Language") { notification.Language = field.Value.S; } if (field.Key == "Try") { notification.Try = int.Parse(field.Value.N); } } return(notification); }
public void ProcessElement(StreamRecord <TInput> element) { var mapped = UserFunction.Map(element.Value); //Output.Collect(element.Replace(mapped)); }
private async Task FinalMessageUpdateAsync(StreamToCheck streamToCheck, StreamRecord record) { List <StreamGame> games; using (var db = new DggContext()) { var latest = db.StreamGames .FirstOrDefault(g => g.StreamId == record.StreamId && g.StopTime == null); if (latest != null) { latest.StopTime = DateTime.UtcNow; await db.SaveChangesAsync(); } games = await db.StreamGames.Where(g => g.StreamId == record.StreamId).ToListAsync(); } record.StartTime = DateTime.SpecifyKind(record.StartTime, DateTimeKind.Utc); var streamDuration = DateTime.UtcNow - record.StartTime; var startTime = TimeZoneInfo.ConvertTime(record.StartTime, Helpers.CentralTimeZone()); var stopTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, Helpers.CentralTimeZone()); var msg = new StringBuilder(streamToCheck.FriendlyUsername + " was live.\n\n"); msg.Append("**Started at:** "); msg.Append(startTime.ToString("HH:mm")); msg.Append(" Central\n"); msg.Append("**Ended at:** "); msg.Append(stopTime.ToString("HH:mm")); msg.Append(" Central\n"); msg.Append("_(total of "); msg.Append(streamDuration.ToFriendlyString()); msg.Append(")_\n\n"); msg.Append("__Games Played__"); foreach (var g in games) { // i dunno why it's putting an empty game for 0 minutes first each time, // but here's a quick fix lel if (string.IsNullOrEmpty(g.Game)) { continue; } g.StopTime = DateTime.SpecifyKind(g.StopTime.Value, DateTimeKind.Utc); g.StartTime = DateTime.SpecifyKind(g.StartTime, DateTimeKind.Utc); var duration = g.StopTime.Value - g.StartTime; msg.Append("\n**"); msg.Append(g.Game); msg.Append(":** "); msg.Append(duration.ToFriendlyString()); } try { var channel = _client.GetChannel((ulong)streamToCheck.DiscordChannelId) as SocketTextChannel; var existingMsg = await channel.GetMessageAsync((ulong)record.DiscordMessageId) as RestUserMessage; await existingMsg.ModifyAsync(m => { m.Content = msg.ToString(); m.Embed = null; }); } catch (Exception ex) { Console.Error.WriteLine("[" + DateTime.UtcNow + "] TWITCH ERROR, FinalMessageUpdateAsync"); Console.Error.WriteLine(ex.ToString()); Console.Error.WriteLine(ex.InnerException?.ToString()); Console.Error.WriteLine("------------"); Console.Error.WriteLine(); } }
public override EvaluateReactionRegistrationResult Execute( EvaluateReactionRegistrationOp operation) { if (operation.ReactionRegistration.Dependencies.Count != 1) { throw new NotSupportedException(Invariant($"Only 1 single {typeof(RecordFilterReactorDependency)} is supported, {operation.ReactionRegistration.Dependencies.Count} were supplied.")); } var dependency = operation.ReactionRegistration.Dependencies.Single(); var recordFilterDependency = dependency as RecordFilterReactorDependency; if (recordFilterDependency == null) { throw new NotSupportedException(Invariant($"Only {typeof(RecordFilterReactorDependency)} is supported, {dependency?.GetType().ToStringReadable()}.")); } var reactionId = Invariant($"{operation.ReactionRegistration.Id}___{DateTime.UtcNow.ToStringInvariantPreferred()}"); var streamRepToHandledDependencyRecordIdToBeIncludedMap = new Dictionary <IStreamRepresentation, HashSet <long> >(); var handledRecordMementos = new List <RecordSetHandlingMemento>(); var allRequiredSeen = true; foreach (var recordFilterEntry in recordFilterDependency.Entries) { try { var stream = this.streamFactory.Execute(new GetStreamFromRepresentationOp(recordFilterEntry.StreamRepresentation)); stream.MustForOp(nameof(stream)).BeAssignableToType <ISyncReturningProtocol <StandardTryHandleRecordOp, TryHandleRecordResult> >(); var streamProtocol = (ISyncReturningProtocol <StandardTryHandleRecordOp, TryHandleRecordResult>)stream; var tryHandleConcern = EvaluateReactionRegistrationOp.BuildHandlingConcern(operation.ReactionRegistration, recordFilterEntry); var handledIds = new HashSet <long>(); // this is because we could get duplicates... StreamRecord currentRecord = null; do { var tryHandleRecordOp = new StandardTryHandleRecordOp( tryHandleConcern, recordFilterEntry.RecordFilter, streamRecordItemsToInclude: StreamRecordItemsToInclude.MetadataOnly, tags: new[] { new NamedValue <string>(TagNames.PotentialReactionId, reactionId), }); var tryHandleRecordResult = streamProtocol.Execute(tryHandleRecordOp); currentRecord = tryHandleRecordResult?.RecordToHandle; if (currentRecord != null) { handledIds.Add(currentRecord.InternalRecordId); } }while (currentRecord != null); if (handledIds.Any()) { var streamProtocolFactoryForActions = (IStreamRecordHandlingProtocolFactory)stream; var streamHandlingProtocolForActions = streamProtocolFactoryForActions.GetStreamRecordHandlingProtocols(); void CompleteAction() { foreach (var handledInternalRecordId in handledIds) { var completeHandlingOp = new CompleteRunningHandleRecordOp( handledInternalRecordId, tryHandleConcern); streamHandlingProtocolForActions.Execute( completeHandlingOp); } } void CancelAction() { foreach (var handledInternalRecordId in handledIds) { var cancelHandlingOp = new CancelRunningHandleRecordOp( handledInternalRecordId, tryHandleConcern, "Not all required dependencies present."); streamHandlingProtocolForActions.Execute( cancelHandlingOp); } } var actionableSetForTracking = new RecordSetHandlingMemento(CompleteAction, CancelAction); handledRecordMementos.Add(actionableSetForTracking); if (recordFilterEntry.IncludeInReaction) { if (streamRepToHandledDependencyRecordIdToBeIncludedMap.ContainsKey(recordFilterEntry.StreamRepresentation)) { streamRepToHandledDependencyRecordIdToBeIncludedMap[recordFilterEntry.StreamRepresentation].AddRange(handledIds); } else { streamRepToHandledDependencyRecordIdToBeIncludedMap.Add(recordFilterEntry.StreamRepresentation, handledIds); } } } else { if (recordFilterEntry.RequiredForReaction && !operation.OverrideRequired) { allRequiredSeen = false; break; } } } catch (Exception ex) { throw new ReactorException(Invariant($"Failed to process entry: {recordFilterEntry}."), ex, operation); } } EvaluateReactionRegistrationResult result; if (!allRequiredSeen) { foreach (var recordSetHandlingMemento in handledRecordMementos) { recordSetHandlingMemento.CancelSet(); } // no reaction created since not all requirement met. result = new EvaluateReactionRegistrationResult(null, new List <RecordSetHandlingMemento>()); } else if (!handledRecordMementos.Any()) { // no reaction created since there wasn't anything to react to. result = new EvaluateReactionRegistrationResult(null, new List <RecordSetHandlingMemento>()); } else { var streamRepresentationToInternalRecordIdsMap = streamRepToHandledDependencyRecordIdToBeIncludedMap.ToDictionary( k => k.Key, v => (IReadOnlyList <long>)v.Value.ToList()); var reactionTags = (operation.ReactionRegistration.Tags ?? new List <NamedValue <string> >()) .Union( new[] { new NamedValue <string>( TagNames.ReactionRegistrationId, operation.ReactionRegistration.Id), }) .ToList(); var reactionEvent = new ReactionEvent( reactionId, operation.ReactionRegistration.Id, operation.ReactionRegistration.ReactionContext, streamRepresentationToInternalRecordIdsMap, DateTime.UtcNow, reactionTags); result = new EvaluateReactionRegistrationResult(reactionEvent, handledRecordMementos); } return(result); }