Exemple #1
0
        /// <summary>
        /// This method Unsubscribe
        /// </summary>
        public void Unsubscribe(Guid id)
        {
            // if the value for HasSubscribers is true
            if ((HasSubscribers) && (Subscribers.Count > 0))
            {
                // attempt to find this callback
                SubscriberCallback callback = Subscribers.FirstOrDefault(x => x.Id == id);

                // If the callback object exists
                if (NullHelper.Exists(callback))
                {
                    // Remove this item
                    Subscribers.Remove(callback);

                    // create a new message
                    SubscriberMessage message = new SubscriberMessage();

                    // set the message return properties
                    message.FromId          = ServerId;
                    message.FromName        = "Subscriber Service";
                    message.Text            = callback.Name + " has left the conversation.";
                    message.ToId            = Guid.Empty;
                    message.ToName          = "Room";
                    message.IsSystemMessage = true;

                    // Broadcast the message to everyone
                    BroadcastMessage(message);
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// This method Broadcasts a Message to everyone that ins't blocked.
        /// What it actually does is notify the Listener that they need to get new messages.
        /// Note To Self: Add Blocked Feature.
        /// </summary>
        public void BroadcastMessage(SubscriberMessage message)
        {
            // if the value for HasSubscribers is true
            if ((HasSubscribers) && (NullHelper.Exists(message)))
            {
                // if this is a System Message
                if (!message.IsSystemMessage)
                {
                    // if there are already messages
                    if (ListHelper.HasOneOrMoreItems(messages))
                    {
                        // Insert at the top
                        Messages.Insert(0, message);
                    }
                    else
                    {
                        // Add this message
                        Messages.Add(message);
                    }
                }

                // Iterate the collection of SubscriberCallback objects
                foreach (SubscriberCallback subscriber in Subscribers)
                {
                    // Send to everyone but this user
                    if ((subscriber.HasCallback) && (subscriber.Id != message.FromId))
                    {
                        // to do: Add if not blocked

                        // send the message
                        subscriber.Callback(message);
                    }
                }
            }
        }
        public IHttpActionResult DeleteSubscriber(int subscriberId)
        {
            SubscriberRequest request = new SubscriberRequest
            {
                SubscriberDto = new SubscriberDto {
                    SubscriberId = subscriberId
                }
            };
            List <string>     errors  = ValidateDeleteSubscriber(request);
            SubscriberMessage message = new SubscriberMessage();

            if (errors != null && errors.Any())
            {
                message.ErrorMessage     = SubscriberMessageResource.ValidationErrors;
                message.ErrorType        = ErrorType.ValidationError;
                message.Errors           = new List <string>();
                message.OperationSuccess = false;
                message.Errors.AddRange(errors);
            }
            else
            {
                message = _serviceSubscriberClient.DeleteSubscriber(request);
            }
            return(Json(message));
        }
Exemple #4
0
        /// <summary>
        /// method returns a message with their id
        /// </summary>
        public SubscriberMessage Subscribe(SubscriberCallback subscriber)
        {
            // initial value
            SubscriberMessage message = null;

            // If the subscriber object exists
            if ((NullHelper.Exists(subscriber)) && (HasSubscribers))
            {
                // Add this item
                Subscribers.Add(subscriber);

                // return a test message for now
                message = new SubscriberMessage();

                // set the message return properties
                message.FromName = "Subscriber Service";
                message.FromId   = ServerId;
                message.ToName   = subscriber.Name;
                message.ToId     = subscriber.Id;
                message.Data     = Subscribers.Count.ToString();
                message.Text     = "Subscribed";
            }

            // return value
            return(message);
        }
Exemple #5
0
        internal static void HandleAndCommitAndPost(
            SubscriberMessage message,
            PublishersBySubscription publishersBySubscription,
            NotificationsByCorrelationsFunction <TUowProvider> notificationsByCorrelationsFunction,
            PublisherVersionByCorrelationsFunction <TUowProvider> publisherVersionByCorrelationsFunction,
            SaveNotificationsByPublisherAndVersionAction <TUowProvider> saveNotificationsByPublisherAndVersionAction,
            CommitWork <TUowProvider> commitWork,
            Action <IEnumerable <IDomainEvent> > publish)
        {
            var list = new List <IDomainEvent>();

            commitWork(provider =>
            {
                Handle(
                    message,
                    publishersBySubscription,
                    notificationsByCorrelationsFunction(provider),
                    publisherVersionByCorrelationsFunction(provider),
                    () => DateTimeOffset.Now,
                    saveNotificationsByPublisherAndVersionAction(provider),
                    messages => list.AddRange(messages));
            });

            publish(list);
        }
Exemple #6
0
        /// <summary>
        /// This method Send Message
        /// </summary>
        public void SendMessage(bool isPrivate = false, SubscriberCallback subscriber = null)
        {
            // Create a new instance of a 'SubscriberMessage' object.
            SubscriberMessage message = null;

            // Create a new instance of a 'SubscriberMessage' object.
            message          = new SubscriberMessage();
            message.Text     = MessageText;
            message.FromId   = Id;
            message.FromName = SubscriberName;
            message.SentTime = DateTime.Now;

            // Set the Time
            message.Sent = DateTime.Now;

            // Set the
            message.BubbleColor = (BubbleColorEnum)Shuffler.PullNextItem();

            try
            {
                // If the MessageText string exists
                if (TextHelper.Exists(MessageText))
                {
                    // if this is a private message
                    if ((isPrivate) && (NullHelper.Exists(subscriber)) && (subscriber.HasCallback))
                    {
                        // Set the ToName
                        message.ToName = subscriber.Name;
                        message.ToId   = subscriber.Id;

                        // This is a private message
                        message.IsPrivate = true;

                        //  Send this message to all clients
                        SubscriberService.SendPrivateMessage(subscriber, message);
                    }
                    else
                    {
                        // Set the ToName
                        message.ToName = "Room";
                        message.ToId   = Guid.Empty;

                        //  Send this message to all clients
                        SubscriberService.BroadcastMessage(message);
                    }

                    // Erase the Text
                    MessageText = "";

                    // Deliver the message to this client, without being Broadcast
                    Listen(message);
                }
            }
            catch (Exception error)
            {
                // for debugging only
                DebugHelper.WriteDebugError("BroadCastMessage", "Chat.razor.cs", error);
            }
        }
        public async Task EnqueueMessageAsync(SubscriberMessage message)
        {
            logger.LogInformation("Adding Message To Queue");
            var entity = mapper.Map <SubscriberMessageEntity>(message);

            context.SubscriberMessages.Add(entity);
            await context.SaveChangesAsync();
        }
Exemple #8
0
 public JsonMessage(SubscriberMessage subscriberMessage)
 {
     NotificationContent = new JsonContent(subscriberMessage.Event.Notification);
     NotificationType    = subscriberMessage.Event.Notification.GetType();
     Subscription        = new JsonContent(subscriberMessage.Subscription);
     SubscriptionType    = subscriberMessage.Subscription.GetType();
     HandlerAddress      = subscriberMessage.Subscription.SubscriberDataContract.Value.ToLower();
     EventId             = subscriberMessage.Event.EventId;
 }
Exemple #9
0
        /// <summary>
        /// This event registers with the chat server
        /// </summary>
        public void RegisterWithServer()
        {
            SubscriberCallback callback = new SubscriberCallback(SubscriberName);

            callback.Callback = Listen;
            callback.Name     = SubscriberName;

            // Get a message back
            SubscriberMessage message = SubscriberService.Subscribe(callback);

            // if message.Text exists and equals Subscribed
            if ((NullHelper.Exists(message)) && (message.HasText) && (TextHelper.IsEqual(message.Text, "Subscribed")))
            {
                // Set to true
                Connected = true;

                // Set the Id the Server assigned
                this.Id = message.ToId;
            }

            // Convert the Subscribers to Names
            this.Names = SubscriberService.GetSubscriberNames();

            // get the count
            int count = NumericHelper.ParseInteger(message.Data.ToString(), 0, -1);

            // if there are two people online or more
            if (count > 1)
            {
                // send a message to everyone else this user has joined
                SubscriberMessage newMessage = new SubscriberMessage();

                // set the text
                newMessage.FromId          = Id;
                newMessage.FromName        = SubscriberName;
                newMessage.Text            = SubscriberName + " has joined the conversation.";
                newMessage.ToId            = Guid.Empty;
                newMessage.ToName          = "Room";
                newMessage.IsSystemMessage = true;

                // Send the message
                SubscriberService.BroadcastMessage(newMessage);

                // 6.5.2020: Get the Messages as you connect now
                this.Messages = SubscriberService.GetBroadcastMessages(this.Id, DisplayMessagesCount);
            }

            // Update
            Refresh();
        }
        /// <summary>
        /// Delete Subscriber
        /// </summary>
        /// <param name="request">subscriber request.</param>
        /// <returns>Subscriber message.</returns>
        public SubscriberMessage DeleteSubscriber(SubscriberRequest request)
        {
            SubscriberMessage message = new SubscriberMessage();

            try
            {
                _serviceSubscriber.DeleteSubscriber(request.ToPivot());
                message.OperationSuccess = true;
            }
            catch (Exception e)
            {
                message.ErrorType    = ErrorType.TechnicalError;
                message.ErrorMessage = e.Message;
            }
            return(message);
        }
        /// <summary>
        /// Get list of Subscriber
        /// </summary>
        /// <returns>Subscriber message.</returns>
        public SubscriberMessage GetAllSubscribers()
        {
            SubscriberMessage message = new SubscriberMessage();

            try
            {
                message = _serviceSubscriber.GetAllSubscribers().ToMessage();
                message.OperationSuccess = true;
            }
            catch (Exception e)
            {
                message.ErrorType    = ErrorType.TechnicalError;
                message.ErrorMessage = e.Message;
            }
            return(message);
        }
Exemple #12
0
        internal static void Handle(
            SubscriberMessage message,
            ProjectorsBySubscription <TProjectorUowProvider> projectorsBySubscription,
            NotificationsByCorrelations notificationsByCorrelations,
            Func <DateTimeOffset> clock,
            TProjectorUowProvider integrationProvider)
        {
            var consumer = projectorsBySubscription[message.Subscription];

            consumer
            (
                message.Event,
                notificationsByCorrelations,
                clock,
                integrationProvider
            );
        }
Exemple #13
0
        public static SubscriberMessage AsSubscriberMessage(this JsonMessage message)
        {
            var subscriberMessage = new SubscriberMessage
            {
                Subscription = (Subscription)JsonConvert.DeserializeObject(
                    message.Subscription.Value,
                    message.SubscriptionType),
                Event = new Event
                {
                    Notification = (INotification)JsonConvert.DeserializeObject(
                        message.NotificationContent.Value,
                        message.NotificationType),
                    EventId = message.EventId
                }
            };

            return(subscriberMessage);
        }
        public IHttpActionResult FindSubscribers(SubscriberRequest request)
        {
            List <string>     errors  = ValidateFindSubscribers(request);
            SubscriberMessage message = new SubscriberMessage();

            if (errors != null && errors.Any())
            {
                message.ErrorMessage     = SubscriberMessageResource.ValidationErrors;
                message.ErrorType        = ErrorType.ValidationError;
                message.Errors           = new List <string>();
                message.OperationSuccess = false;
                message.Errors.AddRange(errors);
            }
            else
            {
                message = _serviceSubscriberClient.FindSubscribers(request);
            }
            return(Json(message));
        }
Exemple #15
0
        /// <summary>
        /// This method Send Private Message
        /// </summary>
        public void SendPrivateMessage(SubscriberCallback subscriber, SubscriberMessage message)
        {
            // if the message and the subscriber exists and the subscriber has a callback
            if ((NullHelper.Exists(message, subscriber)) && (subscriber.HasCallback))
            {
                // if there are already messages
                if (ListHelper.HasOneOrMoreItems(messages))
                {
                    // Insert at the top
                    Messages.Insert(0, message);
                }
                else
                {
                    // Add this message
                    Messages.Add(message);
                }

                // Send the message to the user
                subscriber.Callback(message);
            }
        }
Exemple #16
0
 internal static void HandleAndCommit(
     SubscriberMessage message,
     ProjectorsBySubscription <TProjectorUowProvider> projectorsBySubscription,
     Handler <TProjectorUowProvider> handler,
     NotificationsByCorrelationsFunction <TEventStoreUowProvider> notificationsByCorrelationsFunction,
     CommitWork <TProjectorUowProvider> commitProjectionProvider,
     CommitWork <TEventStoreUowProvider> commitEventStoreProvider,
     Func <DateTimeOffset> clock)
 {
     commitProjectionProvider
     (
         projectionProvider => commitEventStoreProvider
         (
             eventStoreProvider => handler
             (
                 message,
                 projectorsBySubscription,
                 notificationsByCorrelationsFunction(eventStoreProvider),
                 clock,
                 projectionProvider
             )
         )
     );
 }
Exemple #17
0
        /// <summary>
        /// This method Listen
        /// </summary>
        public void Listen(SubscriberMessage message)
        {
            // if the message exists
            if (NullHelper.Exists(message))
            {
                // if the message is a SystemMessage
                if (message.IsSystemMessage)
                {
                    // Get the Names again
                    this.Names = SubscriberService.GetSubscriberNames();

                    // Update the UI
                    Refresh();
                }
                else
                {
                    // Get the Messages
                    this.Messages = SubscriberService.GetBroadcastMessages(this.Id, DisplayMessagesCount);

                    // Update the UI
                    Refresh();
                }
            }
        }
Exemple #18
0
        internal static void Handle(
            SubscriberMessage message,
            PublishersBySubscription publishersBySubscription,
            NotificationsByCorrelations notificationsByCorrelations,
            Func <IEnumerable <Correlation>, int> publisherVersionByPublisherDataContractCorrelations,
            Func <DateTimeOffset> clock,
            Action <NotificationsByPublisherAndVersion> saveNotificationsByPublisherAndVersion,
            Action <IEnumerable <IDomainEvent> > notify)
        {
            var publisher = publishersBySubscription[message.Subscription];

            var notificationsByPublisher = publisher(
                message.Event,
                notificationsByCorrelations,
                clock);

            var notificationsByPublisherAndVersion = Functions.AppendPublisherVersion(
                notificationsByPublisher,
                publisherVersionByPublisherDataContractCorrelations);

            saveNotificationsByPublisherAndVersion(notificationsByPublisherAndVersion);

            notify(notificationsByPublisher.Notifications.Select(x => x.Item1));
        }
Exemple #19
0
        public async Task Delivery_On_With_Messages()
        {
            // Setup
            SetupScopeMock();
            Mock.Get(serviceProvider)
            .Setup(p => p.GetService(It.Is <Type>(v => v == typeof(ISubscriberQueueStore))))
            .Returns(subscriberQueueStore);
            Mock.Get(serviceProvider)
            .Setup(p => p.GetService(It.Is <Type>(v => v == typeof(IDeliveryService))))
            .Returns(deliveryService);
            Mock.Get(serviceProvider)
            .Setup(p => p.GetService(It.Is <Type>(v => v == typeof(ISubscriberStore))))
            .Returns(subscriberStore);

            Mock.Get(subscriberStore)
            .Setup(s => s.GetSubscriber(It.Is <string>(v => v == "sub1")))
            .ReturnsAsync(new Subscriber {
                BaseUri = new Uri("https://server1/"), State = SubscriberStates.Active
            })
            .Verifiable();
            Mock.Get(subscriberStore)
            .Setup(s => s.GetSubscriber(It.Is <string>(v => v == "sub2")))
            .ReturnsAsync(new Subscriber {
                BaseUri = new Uri("https://server2/"), State = SubscriberStates.Active
            })
            .Verifiable();
            Mock.Get(subscriberQueueStore)
            .Setup(s => s.SubscriberIdsWithPendingMessages())
            .ReturnsAsync(new[] { "sub1", "sub2" })
            .Verifiable();
            var msg1 = new SubscriberMessage()
            {
                DestinationUri = new Uri("https://server1/path"), MessageId = 234L, SubscriberId = "sub1", JsonBody = "test"
            };

            Mock.Get(subscriberQueueStore)
            .Setup(s => s.PeekMessageAsync(It.Is <string>(v => v == "sub1")))
            .ReturnsAsync(msg1)
            .Verifiable();
            Mock.Get(subscriberQueueStore)
            .Setup(s => s.ClearMessageAsync(It.Is <long>(v => v == 234L)))
            .Callback(() => { msg1 = null; })
            .Returns(Task.CompletedTask)
            .Verifiable();
            var msg2 = new SubscriberMessage()
            {
                DestinationUri = new Uri("https://server2/path"), MessageId = 544L, SubscriberId = "sub2", JsonBody = "test"
            };

            Mock.Get(subscriberQueueStore)
            .Setup(s => s.PeekMessageAsync(It.Is <string>(v => v == "sub2")))
            .ReturnsAsync(msg2)
            .Verifiable();
            Mock.Get(subscriberQueueStore)
            .Setup(s => s.ClearMessageAsync(It.Is <long>(v => v == 544L)))
            .Callback(() => { msg2 = null; })
            .Returns(Task.CompletedTask)
            .Verifiable();
            Mock.Get(deliveryService)
            .Setup(d => d.DeliverMessage(It.Is <Uri>(v => v == new Uri("https://server1/path")), It.IsAny <string>()))
            .ReturnsAsync(DeliveryResult.Success(System.Net.HttpStatusCode.OK, null))
            .Verifiable();
            Mock.Get(deliveryService)
            .Setup(d => d.DeliverMessage(It.Is <Uri>(v => v == new Uri("https://server2/path")), It.IsAny <string>()))
            .ReturnsAsync(DeliveryResult.Success(System.Net.HttpStatusCode.OK, null))
            .Verifiable();

            // Test
            var service     = new HostedDeliveryService(new TriggerService(), serviceProvider, logger, options);
            var tokenSource = new CancellationTokenSource();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            service.StartAsync(tokenSource.Token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            // Asserts
            await Task.Delay(200);   // Artificial Delay to allow Processing

            Mock.Get(subscriberQueueStore).Verify();
            Mock.Get(deliveryService).Verify();
            Mock.Get(subscriberStore).Verify();
        }
Exemple #20
0
        public bool HaveColumn(string columnName, string columnValue, out bool retValueMatched)
        {
            bool ret          = false;
            bool valueMatched = false;

            if (columnName == "SubscriberID")
            {
                ret = true;
                if (SubscriberID.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "SubscriberGUID")
            {
                ret = true;
                if (SubscriberGUID.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "RevisionNo")
            {
                ret = true;
                if (RevisionNo.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "SubscriberMessage")
            {
                ret = true;
                if (SubscriberMessage.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "SubscriberEmail")
            {
                ret = true;
                if (SubscriberEmail.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "CreatedDate")
            {
                ret = true;
                if (CreatedDate.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "LastUpdateDate")
            {
                ret = true;
                if (LastUpdateDate.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            if (columnName == "IsDeleted")
            {
                ret = true;
                if (IsDeleted.ToString() == columnValue)
                {
                    valueMatched = true;
                }
            }
            retValueMatched = valueMatched;
            return(ret);
        }
 public Task EnqueueMessageAsync(SubscriberMessage message)
 {
     message.MessageId = nextId++;
     store.TryAdd(message.MessageId, message);
     return(Task.FromResult(message.MessageId));
 }
        public IHttpActionResult GetAllSubscribers()
        {
            SubscriberMessage message = _serviceSubscriberClient.GetAllSubscribers();

            return(Json(message));
        }