public async Task SendAsync <TEvent>(IEventNotification <TEvent> context, CancellationToken cancellationToken = default) where TEvent : IEvent
        {
            cancellationToken.ThrowIfCancellationRequested();

            var client = await _topicClientFactory.CreateAsync();

            var message = _messageFactory.CreateMessage(context);

            _logger.LogInformation($"Sending message 1 of 1. Type: '{message.Label}' | Size: '{message.Size}' bytes");

            await client.SendAsync(message);
        }
        public async Task SendAsync<TEvent>(IEventNotification<TEvent> context, CancellationToken cancellationToken = default) where TEvent : IEvent
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            var message = _messageFactory.CreateMessage(context);

            using (var connection = await _connectionFactory.CreateConnectionAsync(cancellationToken))
            {
                await connection.PublishAsync(message, cancellationToken);
            }
        }
Esempio n. 3
0
        private void ProcessReading()
        {
            while (true)
            {
                byte[] buffer = new byte[BufferSize];
                int    bytesRead;

                lock (_syncRoot)
                    bytesRead = _stream.Read(buffer, 0, BufferSize);

                if (bytesRead == 0)
                {
                    continue;
                }

                byte[] packetBytes = new byte[bytesRead];
                Array.Copy(buffer, 0, packetBytes, 0, bytesRead);
                IEnumerable <Packet> packets = _packetHandler.HandlePackets(packetBytes);

                foreach (Packet packet in packets)
                {
                    IMessage message = _messageFactory.CreateMessage(packet.Payload, packet.MessageId);

                    if (message != null)
                    {
                        NotifyForMessage(message);
                    }
                }
            }
        }
Esempio n. 4
0
        public async Task <MessageEnvelope> Poll(CancellationToken cancellationToken)
        {
            var table = new DataTable();

            using (var connection = _connectionFactory())
            {
                if (connection.State != ConnectionState.Open)
                {
                    await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
                }

                using (var command = new SqlCommand(_commandText, connection))
                    using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
                    {
                        if (!reader.HasRows)
                        {
                            return(null);
                        }

                        table.Load(reader);
                    }
            }

            return(_messageFactory.CreateMessage(table.Rows[0]));
        }
        /// <summary>
        /// Создание сообщения из указанного файла.
        /// </summary>
        /// <param name="filepath">Путь к файлу.</param>
        /// <returns>Сообщение.</returns>
        private Message TryCreateMessageFromFile(string filepath, string classId)
        {
            try
            {
                if (System.IO.File.GetLastWriteTime(filepath) > getLastWriteTimeToMemorry(classId))
                {
                    var message = _messageFactory.CreateMessage("File");

                    message.AddPropertyWithValue("OriginalFileName", Path.GetFileName(filepath));
                    message.Body    = System.IO.File.ReadAllBytes(filepath);
                    message.ClassId = classId;

                    addLastWriteTime(System.IO.File.GetLastWriteTime(filepath), classId);

                    return(message);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Не удалось создать сообщения из файла {0}", filepath), ex);
                return(null);
            }
        }
Esempio n. 6
0
        public async Task Run(string subject)
        {
            var cancelationTokenSource = new CancellationTokenSource();

            while (!cancelationTokenSource.Token.IsCancellationRequested)
            {
                try
                {
                    if (!IsConnected)
                    {
                        Reconnect(subject);
                    }
                    var newMessage = _messageFactory.CreateMessage(_iteratorHelper.CurrentIterator);

                    _connection.Publish(subject, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newMessage)));
                    _iteratorHelper.CurrentIterator++;

                    Console.WriteLine("Message has been sent");
                    Thread.Sleep(1000);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            _connection.Close();
        }
        /// <summary>
        /// Sends a private message notification
        /// </summary>
        public static CreateMessageResult SendPrivateMessageNotification(this IMessageFactory factory, Customer customer, PrivateMessage privateMessage, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(privateMessage, nameof(privateMessage));

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.NewPrivateMessage, languageId, privateMessage.StoreId, customer), true, privateMessage));
        }
Esempio n. 8
0
        /// <summary>
        /// Open the given <see cref="Connection"/>.
        /// </summary>
        /// <remarks>
        /// This method is called by
        /// <see cref="Net.Messaging.Impl.Connection.Open"/> and is always run
        /// on client threads.
        /// </remarks>
        /// <param name="connection">
        /// The <b>Connection</b> to open.
        /// </param>
        public override void OpenConnection(Connection connection)
        {
            Debug.Assert(connection != null);

            IChannel        channel0 = InternalChannel;
            IMessageFactory factory0 = channel0.MessageFactory;

            var request = (OpenConnection)
                          factory0.CreateMessage(Util.Daemon.QueueProcessor.Service.Peer.OpenConnection.TYPE_ID);

            IPrincipal principal = System.Threading.Thread.CurrentPrincipal;

            request.ConnectionOpen = connection;
            request.IdentityToken  = SerializeIdentityToken(GenerateIdentityToken(principal));
            request.Principal      = principal;

            var status = (IStatus)channel0.Request(request);

            if (status != null)
            {
                try
                {
                    status.WaitForResponse(ConnectTimeout);
                }
                catch (RequestTimeoutException e)
                {
                    connection.Close(false, e);
                    throw;
                }
            }
        }
Esempio n. 9
0
        public IHttpActionResult SaveRsvp([FromBody] SaveRsvpDto saveRsvp)
        {
            if (!ModelState.IsValid)
            {
                var errors    = ModelState.Values.SelectMany(val => val.Errors).Aggregate("", (current, err) => current + err.Exception.Message);
                var dataError = new ApiErrorDto("RSVP Data Invalid", new InvalidOperationException("Invalid RSVP Data" + errors));
                throw new HttpResponseException(dataError.HttpResponseMessage);
            }
            //validate request
            if (saveRsvp.StartDateUnix <= 0)
            {
                var dateError = new ApiErrorDto("StartDate Invalid", new InvalidOperationException("Invalid Date"));
                throw new HttpResponseException(dateError.HttpResponseMessage);
            }

            return(Authorized(token =>
            {
                var message = _messageFactory.CreateMessage(saveRsvp);
                _eventQueue.Send(message, MessageQueueTransactionType.None);

                // get updated events and return them
                var updatedEvents = new UpdatedEvents();
                try
                {
                    updatedEvents.EventIds.AddRange(_serveService.GetUpdatedOpportunities(token, saveRsvp));
                }
                catch (Exception exception)
                {
                    var apiError = new ApiErrorDto("Save RSVP Failed", exception);
                    throw new HttpResponseException(apiError.HttpResponseMessage);
                }
                return Ok(updatedEvents);
            }));
        }
        private async Task StartSendingMessagesForDeviceAsync(TenantConfiguration tenantConfiguration,
                                                              DeviceInfo deviceInfo, CancellationToken cancellationToken)
        {
            var random = new Random();

            while (!cancellationToken.IsCancellationRequested)
            {
                var objectId = _objectIdsPool
                               .Tenants.First(t => t.Id == tenantConfiguration.Id)
                               .Devices.First(d => d.DeviceId == deviceInfo.DeviceId)
                               .ObjectId;

                var message = _messageFactory.CreateMessage(tenantConfiguration, deviceInfo.DeviceId, objectId, random);

                try
                {
                    await deviceInfo.DeviceClient.SendEventAsync(message, cancellationToken).ConfigureAwait(false);

                    _logger.LogInformation($"Message for Tenant \"{tenantConfiguration.Id}\" DeviceId \"{deviceInfo.DeviceId}\" ObjectId \"{objectId}\" sent.");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Device: {deviceInfo.DeviceId}; Error sending device message: {ex.Message}");
                }

                await Task.Delay(tenantConfiguration.SendingInterval, cancellationToken).ConfigureAwait(false);
            }
        }
Esempio n. 11
0
        public static IMessage CreateTopicMessage(this IMessageFactory <IMessage> socket, byte[] topic)
        {
            var res = socket.CreateMessage();

            res.Append(topic);
            return(res);
        }
Esempio n. 12
0
        /// <inheritdoc />
        public Task SendAsync <TMessage>(TMessage message) where TMessage : IBusTopicMessage
        {
            if (string.IsNullOrEmpty(message.TopicName))
            {
                throw new ApplicationException("Topic name is mandatory");
            }

            var factory = new ConnectionFactory
            {
                Uri = new Uri(_connectionString)
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: message.TopicName, type: "fanout");

                    var body       = _messageFactory.CreateMessage(message);
                    var properties = channel.CreateBasicProperties();
                    _messageFactory.PopulateProperties(message, properties);
                    channel.BasicPublish(exchange: message.TopicName, routingKey: string.Empty, basicProperties: properties, body: body);
                }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Sends 'Return Request status changed' message to a customer
        /// </summary>
        public static CreateMessageResult SendReturnRequestStatusChangedCustomerNotification(this IMessageFactory factory, ReturnRequest returnRequest, OrderItem orderItem, int languageId = 0)
        {
            Guard.NotNull(returnRequest, nameof(returnRequest));
            Guard.NotNull(orderItem, nameof(orderItem));

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.ReturnRequestStatusChangedCustomer, languageId, orderItem.Order?.StoreId, returnRequest.Customer), true, returnRequest));
        }
        /// <summary>
        /// Sends a forum subscription message to a customer
        /// </summary>
        public static CreateMessageResult SendNewForumTopicMessage(this IMessageFactory factory, Customer customer, ForumTopic forumTopic, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(forumTopic, nameof(forumTopic));

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.NewForumTopic, languageId, customer: customer), true, forumTopic, forumTopic.Forum));
        }
        /// <summary>
        /// Synchronously invoke the specified task on each of the specified
        /// members.
        /// </summary>
        /// <remarks>
        /// <p>
        /// This method will not return until the specified members have
        /// completed their processing, failed in their processing, or died
        /// trying.</p>
        /// <p>
        /// <b>IMember</b>s that are specified but are not currently running
        /// the <b>IInvocationService</b> will not invoke the specified
        /// <see cref="IInvocable"/> object.</p>
        /// <p>
        /// <b>IMember</b>s that leave (gracefully or otherwise) before the
        /// invocation completes will not register a result, and the amount
        /// of processing that completed is indeterminate. <b>IMember</b>s
        /// that encounter an exception during invocation will not be
        /// retried; whatever result has been registered by that point by
        /// that member for that <b>IInvocable</b> object will be returned.
        /// Specifically, the result for a given member will be null under
        /// the following conditions:</p>
        /// <list type="bullet">
        /// <item>if the member did not exist</item>
        /// <item>if the member was not running the service at the time that
        /// the query method was invoked</item>
        /// <item>if the member left (via the shutdown or stop methods, or
        /// unexpectedly) before responding</item>
        /// <item>if the member encountered an exception while processing
        /// and had not registered a non-null result</item>
        /// <item>if the member completed successfully but registered no
        /// result</item>
        /// <item>if the member completed successfully but explicitly
        /// registered a result of null</item>
        /// </list>
        /// </remarks>
        /// <param name="task">
        /// The <b>IInvocable</b> object to distribute to the specified
        /// members in order to be invoked on those members.
        /// </param>
        /// <param name="col">
        /// Optional collection of cluster members to which the
        /// <b>IInvocable</b> object will be distributed; if <c>null</c>, the
        /// <b>IInvocable</b> object will be distributed to all cluster
        /// members that are running this service.
        /// </param>
        /// <returns>
        /// An <b>IDictionary</b> of result objects keyed by <see cref="IMember"/>
        /// object.
        /// </returns>
        public virtual IDictionary Query(IInvocable task, ICollection col)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task cannot be null.");
            }

            if (col != null)
            {
                throw new ArgumentException("directed query not supported; " +
                                            "the specified IMember collection must be null.");
            }

            IChannel          channel = EnsureChannel();
            IMessageFactory   factory = channel.MessageFactory;
            InvocationRequest request = (InvocationRequest)factory.CreateMessage(InvocationRequest.TYPE_ID);

            request.Task = task;

            object  result = channel.Request(request);
            IMember member = OperationalContext.LocalMember;

            IDictionary resultDictionary = new HashDictionary();

            resultDictionary.Add(member, result);
            return(resultDictionary);
        }
        /// <summary>
        /// Create a new <see cref="RemoteNamedCache"/> for the given
        /// <see cref="INamedCache"/> name.
        /// </summary>
        /// <param name="name">
        /// The name of the cache.
        /// </param>
        /// <returns>
        /// A new <b>RemoteNamedCache</b>.
        /// </returns>
        public virtual RemoteNamedCache CreateRemoteNamedCache(string name)
        {
            IChannel           channel    = EnsureChannel();
            IConnection        connection = channel.Connection;
            IMessageFactory    factory    = channel.MessageFactory;
            RemoteNamedCache   cache      = new RemoteNamedCache();
            IPrincipal         principal  = Thread.CurrentPrincipal;
            EnsureCacheRequest request    = (EnsureCacheRequest)factory.CreateMessage(EnsureCacheRequest.TYPE_ID);

            request.CacheName = name;
            Uri uri;

            try
            {
                uri = new Uri((string)channel.Request(request));
            }
            catch (UriFormatException e)
            {
                throw new Exception("error instantiating URI", e);
            }

            cache.CacheName                = name;
            cache.CacheService             = this;
            cache.DeferKeyAssociationCheck = DeferKeyAssociationCheck;
            cache.EventDispatcher          = EnsureEventDispatcher();

            connection.AcceptChannel(uri, cache, principal);

            return(cache);
        }
        /// <summary>
        /// Sends a shipment delivered notification to a customer
        /// </summary>
        public static CreateMessageResult SendShipmentDeliveredCustomerNotification(this IMessageFactory factory, Shipment shipment, int languageId = 0)
        {
            Guard.NotNull(shipment, nameof(shipment));
            Guard.NotNull(shipment.Order, nameof(shipment.Order));

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.ShipmentDeliveredCustomer, languageId, shipment.Order.StoreId, shipment.Order.Customer), true, shipment, shipment.Order));
        }
Esempio n. 18
0
 private static void PrintDefault(Party sender, Party receipient)
 {
     using (var msg = factory.CreateMessage("default"))
     {
         msg.Sender    = sender;
         msg.Recipient = receipient;
         msg.Subject   = "Betalingsachterstand";
         msg.Body      = new[]
         {
             "Onlangs heeft u ons opdracht gegeven een applicatie te bouwen om brieven te genereren. Graag willen wij u erop attenderen dat wij hiervoor tot dusver nog geen betaling hebben ontvangen.",
             "Zoals u ziet werkt deze applicatie vlekkeloos. Het genereert, precies volgens de specificaties, een brief in HTML-bestandsopmaak. Deze kunt u vanuit uw browser naar de printer sturen.",
             "Graag ontvangen wij per ommegaande betaling op het bij u bekende bankrekeningnummer."
         };
         msg.Send();
     }
 }
        /// <summary>
        /// Sends a 'Back in stock' notification message to a customer
        /// </summary>
        public static CreateMessageResult SendBackInStockNotification(this IMessageFactory factory, BackInStockSubscription subscription)
        {
            Guard.NotNull(subscription, nameof(subscription));

            var customer   = subscription.Customer;
            var languageId = customer.GetAttribute <int>(SystemCustomerAttributeNames.LanguageId);

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.BackInStockCustomer, languageId, subscription.StoreId, customer), true, subscription.Product));
        }
        /// <summary>
        /// Sends a "Recurring payment cancelled" notification to a store owner
        /// </summary>
        public static CreateMessageResult SendRecurringPaymentCancelledStoreOwnerNotification(this IMessageFactory factory, RecurringPayment recurringPayment, int languageId = 0)
        {
            Guard.NotNull(recurringPayment, nameof(recurringPayment));

            var order = recurringPayment.InitialOrder;

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.RecurringPaymentCancelledStoreOwner, languageId, order?.StoreId, order?.Customer), true,
                                         recurringPayment, order));
        }
Esempio n. 21
0
        /// <inheritdoc />
        public async Task SendQueueMessageAsync <TMessage>(TMessage message) where TMessage : IBusQueueMessage
        {
            if (string.IsNullOrEmpty(message.QueueName))
            {
                throw new ApplicationException("Queue name is mandatory");
            }

            var client = new QueueClient(new ServiceBusConnectionStringBuilder(_connectionString)
            {
                EntityPath = message.QueueName
            });

            var serviceBusMessage = _messageFactory.CreateMessage(message);

            await client.SendAsync(serviceBusMessage);

            await client.CloseAsync();
        }
        /// <summary>
        /// Sends a gift card notification
        /// </summary>
        public static CreateMessageResult SendGiftCardNotification(this IMessageFactory factory, GiftCard giftCard, int languageId = 0)
        {
            Guard.NotNull(giftCard, nameof(giftCard));

            var orderItem = giftCard.PurchasedWithOrderItem;
            var customer  = orderItem?.Order?.Customer;
            var storeId   = orderItem?.Order?.StoreId;

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.GiftCardCustomer, languageId, storeId, customer), true, giftCard, orderItem, orderItem?.Product));
        }
        /// <summary>
        /// Destroy the given <see cref="RemoteNamedCache"/>.
        /// </summary>
        /// <param name="cache">
        /// The <b>RemoteNamedCache</b> to destroy.
        /// </param>
        protected virtual void DestroyRemoteNamedCache(RemoteNamedCache cache)
        {
            ReleaseRemoteNamedCache(cache);

            IChannel            channel = EnsureChannel();
            IMessageFactory     factory = channel.MessageFactory;
            DestroyCacheRequest request = (DestroyCacheRequest)factory.CreateMessage(DestroyCacheRequest.TYPE_ID);

            request.CacheName = cache.CacheName;
            channel.Request(request);
        }
        /// <summary>
        /// Create a new message of the specified type
        /// </summary>
        /// <param name="mimeType">The Mime type</param>
        /// <returns>The new message</returns>
        public AbstractQmsMessage CreateMessage(string mimeType)
        {
            if (mimeType == null || mimeType.Length == 0)
            {
                throw new ArgumentNullException("mimeType");
            }

            IMessageFactory mf = GetFactory(mimeType);

            return(mf.CreateMessage(mimeType));
        }
        /// <summary>
        /// Sends a forum subscription message to a customer
        /// </summary>
        /// <param name="topicPageIndex">Friendly forum topic page to use for URL generation (1-based)</param>
        public static CreateMessageResult SendNewForumPostMessage(this IMessageFactory factory, Customer customer, ForumPost forumPost, int topicPageIndex, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(forumPost, nameof(forumPost));

            var bag = new ModelPart
            {
                ["TopicPageIndex"] = topicPageIndex
            };

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.NewForumPost, languageId, customer: customer), true, bag, forumPost, forumPost.ForumTopic, forumPost.ForumTopic.Forum));
        }
Esempio n. 26
0
        /// <summary>
        /// Sends a "new VAT sumitted" notification to a store owner
        /// </summary>
        public static CreateMessageResult SendNewVatSubmittedStoreOwnerNotification(this IMessageFactory factory, Customer customer, string vatName, string vatAddress, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));

            var model = new NamedModelPart("VatValidationResult")
            {
                ["Name"]    = vatName,
                ["Address"] = vatAddress
            };

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.NewVatSubmittedStoreOwner, languageId, customer: customer), true, model));
        }
        public IHttpActionResult ProcessStripeEvent([FromBody] StripeEvent stripeEvent)
        {
            if (stripeEvent == null || !ModelState.IsValid)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.Debug("Received invalid Stripe event " + stripeEvent);
                }
                return(BadRequest(ModelState));
            }

            _logger.Debug("Received Stripe Event " + stripeEvent.Type);
            if (_liveMode != stripeEvent.LiveMode)
            {
                _logger.Debug("Dropping Stripe Event " + stripeEvent.Type + " because LiveMode was " + stripeEvent.LiveMode);
                return(Ok());
            }

            StripeEventResponseDTO response = null;

            try
            {
                if (_asynchronous)
                {
                    _logger.Debug("Enqueueing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was true");
                    var message = _messageFactory.CreateMessage(stripeEvent);
                    _eventQueue.Send(message, MessageQueueTransactionType.None);
                    response = new StripeEventResponseDTO
                    {
                        Message = "Queued event for asynchronous processing"
                    };
                }
                else
                {
                    _logger.Debug("Processing Stripe event " + stripeEvent.Type + " because AsynchronousProcessingMode was false");
                    response = _stripeEventService.ProcessStripeEvent(stripeEvent);
                }
            }
            catch (Exception e)
            {
                var msg = "Unexpected error processing Stripe Event " + stripeEvent.Type;
                _logger.Error(msg, e);
                var responseDto = new StripeEventResponseDTO()
                {
                    Exception = new ApplicationException(msg, e),
                    Message   = msg
                };
                return(RestHttpActionResult <StripeEventResponseDTO> .ServerError(responseDto));
            }

            return(response == null ? Ok() : (IHttpActionResult)RestHttpActionResult <StripeEventResponseDTO> .Ok(response));
        }
Esempio n. 28
0
        public async Task SendAsync <TMessage>(TMessage message) where TMessage : IBusQueueMessage
        {
            var client = new Microsoft.Azure.ServiceBus.QueueClient(new ServiceBusConnectionStringBuilder(_connectionString)
            {
                EntityPath = message.QueueName
            });

            var serviceBusMessage = _messageFactory.CreateMessage(message);

            await client.SendAsync(serviceBusMessage);

            await client.CloseAsync();
        }
Esempio n. 29
0
        public INngMsg ToMessage <TMsg>(IMessageFactory <TMsg> factory) where TMsg : INngMsg
        {
            var message = factory.CreateMessage();

            if (header.Length > 0)
            {
                message.Header.Append(header.Span);
            }
            if (body.Length > 0)
            {
                message.Append(body.Span);
            }
            return(message);
        }
Esempio n. 30
0
        /// <summary>
        /// Sends wishlist "email a friend" message
        /// </summary>
        public static CreateMessageResult SendShareWishlistMessage(this IMessageFactory factory, Customer customer,
                                                                   string fromEmail, string toEmail, string personalMessage, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));

            var model = new NamedModelPart("Wishlist")
            {
                ["PersonalMessage"] = personalMessage,
                ["From"]            = fromEmail,
                ["To"] = toEmail
            };

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.ShareWishlist, languageId, customer: customer), true, model));
        }