private async Task SubscribeToAll() { var checkpoint = checkpointProvider.Get(); var position = checkpoint.HasValue ? new Position(checkpoint.Value, checkpoint.Value) : Position.Start; subscription = await client.SubscribeToAllAsync(position, OnEvent, subscriptionDropped : OnSubscriptionDropped); }
private async static Task EventArrived( StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray()); var packages = JsonConvert.DeserializeObject <List <Package> >(jsonData); int i = 1; foreach (var package in packages) { Console.WriteLine(); Console.WriteLine($"{i}."); Console.WriteLine($"Package (number: {package.Number}) has been delivered"); Console.WriteLine($"Sender's e-mail: {package.Sender.Email}"); Console.WriteLine($"Receiver's name: {package.Receiver.Name} {package.Receiver.Surname}"); Console.WriteLine($"Receiver's e-mail: {package.Receiver.Email}"); Console.WriteLine($"Receiver's address:"); Console.WriteLine($"{package.Receiver.Address.Street} {package.Receiver.Address.HouseNumber}" + "\n" + $"{package.Receiver.Address.PostCode} {package.Receiver.Address.City}" + "\n" + $"{package.Receiver.Address.Country}"); i++; } SendNotificationEmails(packages); }
private Task HandleNewEvent(StreamSubscription subscription, ResolvedEvent evnt, CancellationToken token) { if (evnt.Event.EventStreamId.StartsWith('$')) { // skip system events return(Task.CompletedTask); } IDomainEvent <IDomainEventData> @event; try { @event = ParseEvent(evnt); } catch { // TODO: Properly handle this case _logger.LogWarning("Unknown event name: {eventName}", evnt.Event.EventType); return(Task.CompletedTask); } _logger.LogDebug("Processed event {position}|{type}.", evnt.OriginalPosition, evnt.Event.EventType); _sender.SendEvent(@event); return(Task.CompletedTask); }
Future <string> join(string separator = "") { _Future result = new _Future(); StringBuilder buffer = new StringBuilder(); StreamSubscription <T> subscription = null; bool first = true; subscription = listen( (T element) => { if (!first) { buffer.Append(separator); } first = false; try { buffer.Append(element); } catch (Exception e) { _stream._cancelAndErrorWithReplacement(subscription, result, e); } }, onError: (e, _) => result._completeError((Exception)e), onDone: () => { result._complete(buffer.ToString()); }, cancelOnError: true); return(result.to <string>()); }
private async Task HandleEvent(StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { var domainEvent = _eventSerializer.Deserialize(resolvedEvent); if (domainEvent == null) { return; } _logger.LogInformation($"PullRequestCommentsProjector handled event: {domainEvent}"); switch (domainEvent) { case SingleCommentWasAdded added: var comment = new PullRequestComment { PullRequestId = added.PullRequestId, CommentId = added.CommentId, PostedAt = added.OccurredAt, Author = added.Author, Text = added.Text }; await _repository.Save(comment); break; } }
public ListviewStreamSubscription(StreamSubscription streamSubscription) { this._streamSubscription = streamSubscription; this.Text = streamSubscription.Name; this.SubItems.Add(streamSubscription.Provider); this.SubItems.Add(streamSubscription.Slug); }
async Task HandleEvent(StreamSubscription streamSubscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { if (resolvedEvent.Event.EventType.StartsWith("$")) { return; } var evt = resolvedEvent.Deserialize(); if (evt == null) { return; } using (var scope = _serviceProvider.CreateScope()) { var publisher = scope.ServiceProvider.GetRequiredService <IPublisher>(); var domainProjectionType = typeof(DomainEventProjection <>).MakeGenericType(evt.GetType()); var domainProjection = Activator.CreateInstance(domainProjectionType, evt) ?? throw new Exception($"Unable to create domain event projection for event {evt.GetType()}"); await publisher.Publish(domainProjection, cancellationToken); _checkpoint.UpdatePosition(resolvedEvent.Event.Position.CommitPosition); await scope.ServiceProvider.GetRequiredService <ICheckpointProvider>() .StoreCheckpoint(_checkpoint, cancellationToken); } }
/// <summary> /// Formats a notification string with the necessary parameters /// </summary> /// <param name="stream"></param> /// <param name="message"></param> /// <returns></returns> public static string GetNotificationMessage(ILiveBotStream stream, StreamSubscription subscription, ILiveBotUser user = null, ILiveBotGame game = null) { string RoleMention = ""; if (subscription.DiscordRole != null) { if (subscription.DiscordRole.Name == "@everyone") { RoleMention = "@everyone"; } else { RoleMention = MentionUtils.MentionRole(subscription.DiscordRole.DiscordId); } } var tempUser = user ?? stream.User; var tempGame = game ?? stream.Game; return(subscription.Message .Replace("{Name}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture) .Replace("{Username}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture) .Replace("{Game}", EscapeSpecialDiscordCharacters(tempGame.Name), ignoreCase: true, culture: CultureInfo.CurrentCulture) .Replace("{Title}", EscapeSpecialDiscordCharacters(stream.Title), ignoreCase: true, culture: CultureInfo.CurrentCulture) .Replace("{URL}", stream.StreamURL ?? "", ignoreCase: true, culture: CultureInfo.CurrentCulture) .Replace("{Role}", RoleMention, ignoreCase: true, culture: CultureInfo.CurrentCulture) .Trim()); }
public async Task <string> ChangeSubscription(int id) { if (id == null) { return("error"); //return NotFound(); } StreamSubscription sub = _context.StreamSubscriptions.Where(ss => ss.ID == id).FirstOrDefault(); DateTime start = DateTime.Now; string @return = "error"; if (sub != null) { switch (sub.Subscribed) { case SubscriptionState.Subscribed: sub.Subscribed = SubscriptionState.Unsubscribed; @return = "false"; break; case SubscriptionState.Unsubscribed: sub.Subscribed = SubscriptionState.Subscribed; @return = "true"; break; } await _context.SaveChangesAsync(); } return(@return); //return RedirectToAction(nameof(Subscriptions)); }
protected async Task Handler(StreamSubscription sub, ResolvedEvent re, CancellationToken cancellationToken) { _debugLog?.Invoke( "Subscription {Subscription} got an event {@Event}", sub.SubscriptionId, re ); _lastProcessedPosition = GetPosition(re); if (re.Event.EventType.StartsWith("$")) { await Store(); } try { var evt = _eventSerializer.Deserialize(re.Event.Data.Span, re.Event.EventType); if (evt != null) { _debugLog?.Invoke("Handling event {Event}", evt); await Task.WhenAll( _projections.Select( x => x.HandleEvent(evt, (long?) re.OriginalPosition?.CommitPosition) ) ); } } catch (Exception e) { _log.LogWarning(e, "Error when handling the event {Event}", re.Event.EventType); } await Store(); Task Store() => StoreCheckpoint(GetPosition(re), cancellationToken); }
private async Task EventAppeared(StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { _logger.LogInformation("{eventType}@{preparePosition}", resolvedEvent.Event.EventType, resolvedEvent.Event.Position.PreparePosition); var e = EventSerializer.Deserialize(resolvedEvent); await ExecuteProjectionHandlers(e); }
private void SubscriptionDropped(StreamSubscription _, SubscriptionDroppedReason reason, Exception ex) { if (ex == null) { return; } _completed.TrySetException(ex); }
void _unsubscribe() { if (_subscription != null) { _subscription.cancel(); _subscription = null; } }
internal _ForwardingStreamSubscription(_ForwardingStream <S, T> _stream, Action <T> onData, Action <object, string> onError, Action onDone, bool cancelOnError ) : base(onData, onError, onDone, cancelOnError) { this._stream = _stream; _subscription = _stream._source .listen(_handleData, onError: _handleError, onDone: _handleDone); }
void _handleDone() { try { _subscription = null; _transformerSink.close(); } catch (Exception e) { _addError(e, e.StackTrace); } }
void HandleDrop(StreamSubscription subscription, SubscriptionDroppedReason reason, Exception?exception) { if (reason == SubscriptionDroppedReason.Disposed) { return; } _started = false; Task.Run(Start); }
/// <summary> /// Removes the specified stream from the cache. /// </summary> /// <param name="streamId">The stream identifier.</param> /// <returns>The <see cref="Task"/></returns> public static async Task UnregisterStream(string streamId) { if (subscriptions.ContainsKey(streamId)) { StreamSubscription subscription = null; while (!subscriptions.TryRemove(streamId, out subscription)) { await Task.Delay(1); } } }
/// <summary> /// Unsubscribes from a topic. /// </summary> /// <param name="streamId">The stream identifier.</param> /// <param name="topic">The topic.</param> public static void UnsubscribeFromTopic(string streamId, string topic) { if (!string.IsNullOrEmpty(topic) && subscriptions.ContainsKey(streamId)) { StreamSubscription subscriptionStream = subscriptions[streamId]; if (subscriptionStream.Topics.Contains(topic)) { subscriptionStream.Topics.Remove(topic); } } }
/// <summary> /// Start the subscription to EventStoreDB /// </summary> /// <param name="cancellationToken"></param> public async Task Start(CancellationToken cancellationToken) { var filter = new SubscriptionFilterOptions(EventTypeFilter.ExcludeSystemEvents()); _subscription = await _client.SubscribeToAllAsync(Position.Start, EventAppeared, subscriptionDropped : SubscriptionDropped, filterOptions : filter, resolveLinkTos : true, cancellationToken : cancellationToken); }
public Future forEach(Action <T> action) { _Future future = new _Future(); StreamSubscription <T> subscription = null; subscription = listen( (T element) => { // TODO(floitsch): the type should be 'void' and inferred. _stream._runUserCode <object>(() => { action(element); return(default);
internal _SinkTransformerStreamSubscription(Stream <S> source, _async._SinkMapper <S, T> mapper, Action <T> onData, Action <object, string> onError, Action onDone, bool cancelOnError) // We set the adapter's target only when the user is allowed to send data. : base(onData, onError, onDone, cancelOnError) { _EventSinkWrapper <T> eventSink = new _EventSinkWrapper <T>(this); _transformerSink = mapper(eventSink); _subscription = source.listen(_handleData, onError: _handleError, onDone: _handleDone); }
private async static Task EventArrived( StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray()); var book = JsonConvert.DeserializeObject <Book>(jsonData); Console.WriteLine(jsonData); }
private async static Task EventArrived( StreamSubscription subscription, ResolvedEvent resolvedEvent, CancellationToken cancellationToken) { var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray()); var packageData = JsonConvert.DeserializeObject <PackageData>(jsonData); SendEmail(packageData); }
public override StreamSubscription <T> listen(Action <T> onData, Action <object, string> onError = null, Action onDone = null, bool cancelOnError = false) { //cancelOnError = cancelOnError; StreamSubscription <T> result = _onListen(_stream, cancelOnError); result.onData(onData); result.onError(onError); result.onDone(onDone); return(result); }
protected override Future _onCancel() { if (_isSubscribed) { StreamSubscription <S> subscription = _subscription; _subscription = null; return(subscription.cancel()); } return(null); }
async Task EventAppeared(StreamSubscription _, ResolvedEvent resolvedEvent, CancellationToken c) { if (resolvedEvent.Event.EventType.StartsWith("$")) { return; } var @event = resolvedEvent.Deserialize() !; await Task.WhenAll( _subscriptions.Select(x => x.Project(@event)) ); }
async Task Subscribe() { var room = system.StreamOf <ChatRoomMessage>("sms", RoomName); subscription = await room.Subscribe((message, _) => { if (message.User != UserName) { Console.WriteLine(message.Text); } }); }
// ------------------------------------------------------------------ // Stream interface. public override StreamSubscription <T> listen( Action <T> onData, Action <object, string> onError = null, Action onDone = null, bool cancelOnError = false) { // void onData(T data), // {Function onError, void onDone(), bool cancelOnError}) { cancelOnError = Equals(true, cancelOnError); StreamSubscription <T> subscription = _createSubscription(onData, onError, onDone, cancelOnError); _onListen(subscription); return(subscription); }
async Task Subscribe() { var room = system.StreamOf(Constants.StreamProviderNameDefault, Constants.StreamNameSpaceCustomers); subscription = await room.Subscribe <ChatRoomMessage>(message => { if (message.User != UserName) { Console.WriteLine(message.Text); } }); }
public async Task Join() { subscription = await room.Subscribe <ChatRoomMessage>(message => { if (message.User != UserName) { Console.WriteLine(message.Text); } }); await user.Tell(new Join { Room = RoomName }); }
private void SubscriptionDropped(StreamSubscription subscription, SubscriptionDroppedReason reason, Exception?exception) { if (exception != null) { _logger.LogError($"PullRequestCommentsProjector dropped due to: {reason}", exception); } else { _logger.LogInformation($"PullRequestCommentsProjector dropped due to: {reason}"); } }
protected override void ParseSubscription() { if (txtName.Text.Trim() == "" || txtSlug.Text.Trim() == "") { MessageBox.Show(i18n.FillStreamNameAndUrlFieldsMessage, i18n.AllFieldsRequiredTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false)); return; } StreamProvider provider = null; this.InvokeHandler(() => { provider = (StreamProvider)Providers.Instance.Dictionary[comboBoxProviders.SelectedItem.ToString().ToLower()]; }); string streamKey = string.Format("{0}@{1}", txtSlug.Text, provider.Name.ToLower()); if (Subscriptions.Instance.Dictionary.ContainsKey(streamKey)) { MessageBox.Show(string.Format(i18n.StreamSubscriptionAlreadyExistsMessage, Subscriptions.Instance.Dictionary[streamKey].Name), i18n.SubscriptionExists, MessageBoxButtons.OK, MessageBoxIcon.Error); this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false)); return; } try { var subscription = new StreamSubscription { Name = txtName.Text, Slug = txtSlug.Text, Provider=provider.Name }; using (var stream = StreamFactory.CreateStream(subscription)) { if (!stream.IsValid()) { MessageBox.Show(i18n.ErrorParsingStreamMessage, i18n.ErrorParsingStreamTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false)); return; } } this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(true, subscription)); } catch (Exception) { MessageBox.Show(i18n.ErrorParsingStreamMessage, i18n.ErrorParsingStreamTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); this.OnSubscriptionParsed(new SubscriptionParsedEventArgs(false)); } }
public JustinTv(StreamSubscription subscription) : base(subscription) { }
public Own3Dtv(StreamSubscription subscription) : base(subscription) { }
public LiveStream(StreamSubscription subscription) : base(subscription) { }