/// <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));
        }
        private async Task HandlePlainText(HttpContext context, ulong auth_key, BinaryReader reader)
        {
            var message_id   = reader.ReadUInt64();
            var message_size = reader.ReadInt32();
            var envelop      = MessageContext.Create(reader.ReadMTObject());

            envelop.AuthKey(auth_key);
            envelop.MessageId(message_id);
            envelop.MessageSize(message_size);
            this.logger.LogDebug(
                "PlainText request received: {0}", envelop.Body);

            var response = await MTServer.Instance.Services.Bus().Send(envelop);

            var writer = new BinaryWriter(context.Response.Body);

            writer.Write(auth_key);
            writer.Write(message_id);
            writer.Write(message_size);
            if (response != null)
            {
                MTObjectSerializer.Serialize(response as MTObject, writer);
                this.logger.LogDebug(
                    $"PlainText request successfully handled. Response: '{response}'");
            }
            else
            {
                this.logger.LogWarning(
                    $"No response for: '{envelop.Body}'");
                //context.Response.StatusCode = 404;
            }
            writer.Close();
        }
Exemple #3
0
        /// <summary>
        /// Sends an "email a friend" message.
        /// </summary>
        /// <param name="factory">Message factory.</param>
        /// <param name="customer">Customer.</param>
        /// <param name="product">Product.</param>
        /// <param name="fromEmail">Sender email address.</param>
        /// <param name="toEmail">Recipient email address.</param>
        /// <param name="personalMessage">Message text.</param>
        /// <param name="languageId">Language identifier.</param>
        /// <returns>Create message result.</returns>
        public static async Task <CreateMessageResult> SendShareProductMessageAsync(
            this IMessageFactory factory,
            Customer customer,
            Product product,
            string fromEmail,
            string toEmail,
            string personalMessage,
            int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(product, nameof(product));

            var model = new NamedModelPart("Message")
            {
                ["Body"] = personalMessage.NullEmpty(),
                ["From"] = fromEmail.NullEmpty(),
                ["To"]   = toEmail.NullEmpty()
            };

            return(await factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.ShareProduct, languageId, customer: customer),
                       true,
                       product,
                       model));
        }
        /// <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));
        }
Exemple #5
0
        /// <summary>
        /// Sends an ask product question message.
        /// </summary>
        /// <param name="factory">Message factory.</param>
        /// <param name="customer">Customer.</param>
        /// <param name="product">Product.</param>
        /// <param name="senderEmail">Sender email address.</param>
        /// <param name="senderName">Sender name.</param>
        /// <param name="senderPhone">Sender phone number.</param>
        /// <param name="question">Question text.</param>
        /// <param name="attributeInfo">Attribute informations.</param>
        /// <param name="productUrl">Product URL.</param>
        /// <param name="isQuoteRequest">A value indicating whether the message is a quote request.</param>
        /// <param name="languageId">Language identifier.</param>
        /// <returns>Create message result.</returns>
        public static async Task <CreateMessageResult> SendProductQuestionMessageAsync(
            this IMessageFactory factory,
            Customer customer,
            Product product,
            string senderEmail,
            string senderName,
            string senderPhone,
            string question,
            string attributeInfo,
            string productUrl,
            bool isQuoteRequest,
            int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(product, nameof(product));

            var model = new NamedModelPart("Message")
            {
                ["ProductUrl"]        = productUrl.NullEmpty(),
                ["IsQuoteRequest"]    = isQuoteRequest,
                ["ProductAttributes"] = attributeInfo.NullEmpty(),
                ["Message"]           = question.NullEmpty(),
                ["SenderEmail"]       = senderEmail.NullEmpty(),
                ["SenderName"]        = senderName.NullEmpty(),
                ["SenderPhone"]       = senderPhone.NullEmpty()
            };

            return(await factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.ProductQuestion, languageId, customer: customer),
                       true,
                       product,
                       model));
        }
        /// <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));
        }
Exemple #7
0
        public async Task <MessageHandlingResult> ProcessMessageAsync(
            Message message, IEndpointHandlingConfig handlingConfig, CancellationToken ct)
        {
            try
            {
                var messageContext = MessageContext.Create(message);

                var contractMessage = _serialiser.Deserialise <TMessage>(message);
                if (contractMessage == null)
                {
                    return(MessageHandlingResult.UnrecognisedMessageType(
                               $"Serialiser could not de-serialise message to {typeof(TMessage).AssemblyQualifiedName}",
                               message.UserProperties));
                }

                var stopwatch      = Stopwatch.StartNew();
                var handlingResult = await _handler.HandleMessageAsync(contractMessage, messageContext, ct).ConfigureAwait(false);

                _instrumentor.TrackElapsed(
                    LogEventIds.HandlerMeasuredElapsed, stopwatch.ElapsedMilliseconds, _handler.GetType().Name, message.UserProperties);

                return(handlingResult);
            }
            catch (OperationCanceledException ex)
            {
                _logger.LogWarning(LogEventIds.ProcessorCancelled, ex, $"Operation was cancelled in Processor<{typeof(TMessage).Name}>");
                return(MessageHandlingResult.Abandoned(ex, message.UserProperties));
            }
        }
        /// <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 "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));
        }
        /// <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));
        }
Exemple #11
0
        /// <summary>
        /// Sends a "quantity below" notification to a store owner.
        /// </summary>
        /// <param name="factory">Message factory.</param>
        /// <param name="product">Product.</param>
        /// <param name="languageId">Language identifier.</param>
        /// <returns>Create message result.</returns>
        public static async Task <CreateMessageResult> SendQuantityBelowStoreOwnerNotificationAsync(this IMessageFactory factory, Product product, int languageId = 0)
        {
            Guard.NotNull(product, nameof(product));

            return(await factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.QuantityBelowStoreOwner, languageId),
                       true,
                       product));
        }
Exemple #12
0
 /// <summary>
 /// Sends a new order note added notification to the customer.
 /// </summary>
 public static Task <CreateMessageResult> SendNewOrderNoteAddedCustomerNotificationAsync(this IMessageFactory factory, OrderNote orderNote, int languageId = 0)
 {
     Guard.NotNull(orderNote, nameof(orderNote));
     return(factory.CreateMessageAsync(
                MessageContext.Create(MessageTemplateNames.OrderNoteAddedCustomer, languageId, orderNote.Order?.StoreId, orderNote.Order?.Customer),
                true,
                orderNote,
                orderNote.Order));
 }
Exemple #13
0
        /// <summary>
        /// Sends a product review notification message to a store owner.
        /// </summary>
        /// <param name="factory">Message factory.</param>
        /// <param name="productReview">Product review</param>
        /// <param name="languageId">Language identifier.</param>
        /// <returns>Create message result.</returns>
        public static async Task <CreateMessageResult> SendProductReviewNotificationMessageAsync(this IMessageFactory factory, ProductReview productReview, int languageId = 0)
        {
            Guard.NotNull(productReview, nameof(productReview));

            return(await factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.ProductReviewStoreOwner, languageId, customer: productReview.Customer),
                       true,
                       productReview,
                       productReview.Product));
        }
        /// <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));
        }
Exemple #15
0
        /// <summary>
        /// Sends an order placed notification to the store owner.
        /// </summary>
        public static Task <CreateMessageResult> SendOrderPlacedStoreOwnerNotificationAsync(this IMessageFactory factory, Order order, int languageId = 0)
        {
            Guard.NotNull(order, nameof(order));

            return(factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.OrderPlacedStoreOwner, languageId, order.StoreId),
                       true,
                       order,
                       order.Customer));
        }
Exemple #16
0
        public async Task should_be_able_to_serialize_context()
        {
            var context = MessageContext.Create(new Message {
                Value = "test"
            }).Cast(null) as IMessageContext <Message>;
            var packet = context.Serialize();

            var message = MTServer.Instance.Services.DeserializeMessage(packet) as IMessageContext <Message>;

            Assert.IsNotNull(context);
        }
        public static async Task <IMessageContext> SendProto(this IBus bus, IMessageContext message, int timeOut = 3000, SendModes mode = SendModes.Both, CancellationToken cancellationToken = default)
        {
            var result = await bus.Send(message, null, timeOut, mode, cancellationToken);

            if (result as IMessageContext != null)
            {
                return(result as IMessageContext);
            }

            return(MessageContext.Create(result));
        }
        /// <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));
        }
Exemple #19
0
        /// <summary>
        /// Sends a 'Back in stock' notification message to a customer.
        /// </summary>
        /// <param name="factory">Message factory.</param>
        /// <param name="subscription">Back in stock subscription.</param>
        /// <returns>Create message result.</returns>
        public static async Task <CreateMessageResult> SendBackInStockNotificationAsync(this IMessageFactory factory, BackInStockSubscription subscription)
        {
            Guard.NotNull(subscription, nameof(subscription));

            var customer   = subscription.Customer;
            var languageId = customer.GenericAttributes.LanguageId ?? 0;

            return(await factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.BackInStockCustomer, languageId, subscription.StoreId, customer),
                       true,
                       subscription.Product));
        }
Exemple #20
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));
        }
Exemple #21
0
        /// <summary>
        /// Sends a new return request message to the store owner.
        /// </summary>
        public static Task <CreateMessageResult> SendNewReturnRequestStoreOwnerNotificationAsync(this IMessageFactory factory, ReturnRequest returnRequest, OrderItem orderItem, int languageId = 0)
        {
            Guard.NotNull(returnRequest, nameof(returnRequest));
            Guard.NotNull(orderItem, nameof(orderItem));

            return(factory.CreateMessageAsync(
                       MessageContext.Create(MessageTemplateNames.NewReturnRequestStoreOwner, languageId, orderItem.Order?.StoreId, returnRequest.Customer),
                       true,
                       returnRequest,
                       orderItem,
                       orderItem.Order,
                       orderItem.Product));
        }
Exemple #22
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));
        }
        public static IMessageContext DeserializeMessage(this IMTServiceProvider services, string packet)
        {
            IMessageContext result  = null;
            MessagePacket   _packet = JsonConvert.DeserializeObject <MessagePacket>(packet);
            object          message = null;

            if (_packet.Data != null && _packet.Data.Length > 1)
            {
                message = _packet.Type == typeof(MTObject).Name
                                        ? MTObjectSerializer.DeserializeEx(_packet.Data)
                                        : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(_packet.Data), Type.GetType(_packet.Type));
            }
            result = MessageContext.Create(message, null, _packet.Headers, serviceProvider: services);
            return(result);
        }
        public static CreateMessageResult SendProductQuestionMessage(this IMessageFactory factory, Customer customer, Product product,
                                                                     string senderEmail, string senderName, string senderPhone, string question, int languageId = 0)
        {
            Guard.NotNull(customer, nameof(customer));
            Guard.NotNull(product, nameof(product));

            var model = new NamedModelPart("Message")
            {
                ["Message"]     = question.NullEmpty(),
                ["SenderEmail"] = senderEmail.NullEmpty(),
                ["SenderName"]  = senderName.NullEmpty(),
                ["SenderPhone"] = senderPhone.NullEmpty()
            };

            return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.ProductQuestion, languageId, customer: customer), true, product, model));
        }
        private async Task <object> ProcessMessage(IMTSession session, InnerMessage message, CancellationToken cancellationToken)
        {
            object result = null;
            ulong  type   = 0;

            try
            {
                type = BitConverter.ToUInt32(message.Content, 0);
                var req = message.Content.ToMTObject();                // session.Services.Serialization().Deserialize(message.Content);
                {
                    this.logger.LogInformation(req.GetType().Name);
                    var envelop = MessageContext.Create(req);
                    envelop.container_seq_no(message.container_seq_no);
                    envelop.container_msg_id(message.container_msg_id);
                    envelop.AuthKey(message.AuthKey);
                    envelop.msg_id(message.msg_id);
                    envelop.seq_no(message.seq_no);
                    var _ret = await serviceProvider.Bus().Send(envelop, cancellationToken: cancellationToken) as MTObject;

                    if (_ret as MTObject != null)
                    {
                        result = new MTRpcResult
                        {
                            ReqMsgId = (long)message.msg_id,
                            Result   = new MTGzipPacked
                            {
                                PackedData = Utils.compress(_ret.ToByteArray())
                            }
                        };
                        session.AddMessage(result as MTObject, true, true);
                    }
                }
            }
            catch (Exception err)
            {
                if (err is InvalidDataException)
                {
                    this.logger.LogWarning(
                        $"Invalid or Not Supported Constructor: '{type.ToString("X4")}'");
                }
                else
                {
                    this.logger.LogError($"An error occured while trying to process this message: {err}");
                }
            }
            return(result);
        }
Exemple #26
0
        public Task Publish(object message, string topic, CancellationToken cancellationToken)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (string.IsNullOrWhiteSpace(topic))
            {
                topic = Extensions.GetTopic(message.GetType());
            }
            if (message as IMessageContext == null)
            {
                message = MessageContext.Create(message, topic);
            }

            return(Task.WhenAll(this.GetSubscriptions(topic).Select(x => x.Handler(message as IMessageContext))));
        }
Exemple #27
0
        public async Task remote_rpc_should_work()
        {
            var host   = this.CreateWebHost();
            var client = AppDomainHelper.Create("test1").GetProxy <TestClient>();

            client.Start(2535);
            await host.StartAsync();

            var bus = host.Services.GetService <IBus>();

            //await bus.ProtoRegister<MTReqPq>(true,subs =>
            //{
            //	subs.Handler = x => {

            //		return Task.FromResult<object>(new MTReqDhParams {
            //			Nonce = new Org.BouncyCastle.Math.BigInteger(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, }),
            //			EncryptedData = new byte[] { 1, 2, 3 },
            //			P = new byte[] { 1, 2, 3 },
            //			PublicKeyFingerprint = 0,
            //			Q = new byte[] { 1, 2, 3 },
            //			ServerNonce = new Org.BouncyCastle.Math.BigInteger( new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, })
            //		}) ;
            //	};

            //});

            var req = new MTReqPq()
            {
                Nonce = new Org.BouncyCastle.Math.BigInteger("12332432543546546456456546456456456456", 10)
            };


            var context = MessageContext.Create(req);

            var reply = await bus.SendProto(message : context, mode : SendModes.ExternalOnly);

            //var obj = reply.B.GetMessage();
            var f = reply.Body;



            await host.StopAsync();

            await Task.Delay(10 * 60 * 1000);
        }
Exemple #28
0
        public async Task <object> Send(object message, string topic = null, int timout = 30000, SendModes mode = SendModes.Both, CancellationToken cancellationToken = default)
        {
            object result = null;

            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (message as IMessageContext == null)
            {
                message = MessageContext.Create(message, topic);
            }
            var context = message as IMessageContext;

            if (string.IsNullOrWhiteSpace(topic))
            {
                topic = Extensions.GetTopic(message.GetType());
            }
            if (mode != SendModes.ExternalOnly)
            {
                foreach (var h in this.GetSubscriptions(topic).Where(x => x.IsRequestHandler))
                {
                    try
                    {
                        result = await h.Handler(context).TimeoutAfter(30000, cancellationToken);

                        return(result);
                    }
                    catch { }
                }
            }
            if (mode != SendModes.InternalOnly && message as IMessageContext != null && this.rabbit.IsActive)
            {
                /// Try to send to remote
                /// Note that we can only send message contexts...
                //var context = message as IMessageContext;
                try
                {
                    var text = context.Serialize();
                    result = await this.rabbit.Send(Encoding.UTF8.GetBytes(text));
                }
                catch { }
            }
            return(result);
        }
Exemple #29
0
 public static CreateMessageResult SendWithdrawalNotificationMessageToUser(this IMessageFactory factory, Transaction transaction, string vatName, string vatAddress, int languageId = 0)
 {
     Guard.NotNull(transaction, nameof(transaction));
     return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.CustomerWithdrawal, languageId, 1, transaction.Customer), true, transaction));
 }
Exemple #30
0
 public static CreateMessageResult SendReferralNotification(this IMessageFactory factory, Customer customer, int languageId = 0)
 {
     Guard.NotNull(customer, nameof(customer));
     return(factory.CreateMessage(MessageContext.Create(MessageTemplateNames.CustomerReferral, languageId, customer: customer), true));
 }