static void Main()
        {
            Console.WriteLine("Using straight xml serialization and msmq to test interop.");
            Console.WriteLine("To exit, enter 'q'. Press 'Enter' to send a message.");

            string queueName = string.Format("FormatName:DIRECT=OS:{0}\\private$\\OrderServiceInputQueue", Environment.MachineName);
            var label = "<CorrId></CorrId><WinIdName>UDI_MOBILE_2\\Administrator</WinIdName>";

            var q = new MessageQueue(queueName);

            var serializer = new XmlSerializer(typeof(OrderMessage), new[] { typeof(OrderLine) });

            while ((Console.ReadLine().ToLower()) != "q")
            {
                var m1 = new OrderMessage
                             {
                                 PurchaseOrderNumber = Guid.NewGuid().ToString(),
                                 ProvideBy = DateTime.Now,
                                 PartnerId = Guid.NewGuid(),
                                 OrderLines = new[] {new OrderLine {ProductId = Guid.NewGuid(), Quantity = 10F}},
                                 Done = true
                             };

                var toSend = new Message();
                serializer.Serialize(toSend.BodyStream, m1);
                toSend.ResponseQueue = new MessageQueue(string.Format("FormatName:DIRECT=OS:{0}\\private$\\PartnerInputQueue", Environment.MachineName));
                toSend.Label = label;

                q.Send(toSend, MessageQueueTransactionType.Single);
                Console.WriteLine("Sent order {0}", m1.PurchaseOrderNumber);
            }
        }
 public void should_notify_order_received_with_mail_sender_address()
 {
     var mailMessage = new OrderMessage
         {
             From = "customer"
         };
     _mailTranslator.Process(mailMessage);
     _orderListener.AssertWasCalled(l=>l.OrderReceived(mailMessage.From));
 }
        public void InstantiateOrder(string email, int salesChannelId, string orderId, int orderAmount)
        {
            var orderMessage = new OrderMessage()
            {
                CustomerEmail = email,
                OrderAmount   = orderAmount,
                OrderId       = orderId
            };

            var backOfficeOrder = _factory.InstantiateFrom(orderMessage, salesChannelId);

            backOfficeOrder.CustomerEmail.ShouldBe(email);
            backOfficeOrder.SalesChannelId.ShouldBe(salesChannelId);
            backOfficeOrder.OrderId.ShouldBe(orderId);
            backOfficeOrder.OrderAmount.ShouldBe(orderAmount);
        }
Example #4
0
        public bool HandleMessage()
        {
            Order          newOrder        = CreateNewOrder(OrderMessage);
            OrderMessage   newOrderMessage = CreateNewOrderMessage(OrderMessage);
            List <BomItem> newBomItems     = CreateNewBomItems(OrderMessage);

            if (newOrder != null && newBomItems.Count > 0)
            {
                if (CreateOrModifyOrderInDatabase(newOrder, newOrderMessage, newBomItems))
                {
                    return(false);
                }
            }

            return(true);
        }
        public IActionResult Get(int id)
        {
            var proInfo = productAPI.GetProduct(id).Result;
            var item    = new OrderMessage
            {
                id              = 1,
                orderId         = "alibaba_20200723161759000_0001",
                createOrderTime = DateTime.Now,
                state           = "未支付",
                total           = 123.59M,
                productInfos    = proInfo,
                userId          = 10001
            };

            return(Ok(item));
        }
Example #6
0
        private async Task <bool> UpdateStorageNumberAsync(OrderMessage order)
        {
            //throw new Exception("test"); // just for demo use
            using (var conn = new SqlConnection(_connStr))
            {
                string sqlCommand = @"UPDATE [dbo].[Storages] SET StorageNumber = StorageNumber - 1
                                                                WHERE StorageID = @ProductID";

                int count = await conn.ExecuteAsync(sqlCommand, param : new
                {
                    ProductID = order.ProductID
                });

                return(count > 0);
            }
        }
Example #7
0
        private static HttpMessageState ConfigureSendOrderState(HttpMessageState s, Log log, Random rng, string endPoint, string user)
        {
            var orderMessage = OrderMessage.GenerateRandomMessage("-1", rng);

            s.Name         = user + ", HttpMessageState::sendOrder";
            s.Uri          = endPoint + "/post-order";
            s.Message      = orderMessage;
            s.SetupMessage = (msg) =>
            {
                orderMessage.token = s.Context.Resolve <string>(UserTokenId);
                orderMessage.Randomize(s.Context.Resolve <Random>());

                s.Context.Register(MessageCountId, s.Context.Resolve <int>(MessageCountId) + 1);

                log?.Put(OutputLevel.Info, s.Name, "sending order with " + orderMessage.items.Length + " items.");
            };
            s.ProcessResponse = async(response) =>
            {
                if (response.IsSuccessStatusCode)
                {
                    var message = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(message))
                    {
                        var serverResponse = JsonSerializer.Deserialize <ServerResponse>(message);

                        s.Context.Register(AckCountId, s.Context.Resolve <int>(AckCountId) + 1);

                        /*if (serverResponse.timeStamp == orderMessage.timeStamp)
                         * {
                         *  s.Context.Register(AckCountId, s.Context.Resolve<int>(AckCountId) + 1);
                         * }*/
                    }
                    else
                    {
                        LogError(log, s.Context, s.Name + " send order received no ack");
                    }
                }
                else
                {
                    LogError(log, s.Context, s.Name + " send order with " + orderMessage.items.Length + " items, received error code."
                             + " - " + response.ReasonPhrase);
                }
            };
            s.SendMethod = RestMethod.POST;
            return(s);
        }
        private void Handle(OrderMessage message)
        {
            Console.WriteLine("Receive message: {0} {1}", message.Id, message.Name);

            if (_simulator.IsBusy)
            {
                Console.WriteLine("STASHING message");
                Stash.Stash();
            }
            else
            {
                Stash.Unstash();
                Console.WriteLine("UNSTASHED all messages");
                _simulator.Proccess(message);
                Console.WriteLine("Message {0} processed", message.Id);
            }
        }
Example #9
0
        public async Task <bool> CreateOrderByDapper(IOrder order)
        {
            using (var conn = new MySqlConnection(ConnStr))
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    // business code here
                    string sqlCommand = @"INSERT INTO orders(OrderID, OrderTime, OrderUserID, ProductID)
                                                                VALUES(@OrderID, @OrderTime, @OrderUserID, @ProductID)";
                    //IDataReader abc = await conn.ExecuteReaderAsync(sqlCommand);
                    //string ab;
                    //while (abc.Read())
                    //{
                    //    ab = abc["a1"].ToString();
                    //}
                    var query = conn.QueryAsync <Order>(sqlCommand);

                    order.ID = GenerateOrderID();
                    await conn.ExecuteAsync(sqlCommand, param : new
                    {
                        OrderID     = order.ID,
                        OrderTime   = DateTime.Now,
                        OrderUserID = order.OrderUserID,
                        ProductID   = order.ProductID
                    }, transaction : trans);

                    // For Dapper/ADO.NET, need to pass transaction
                    var orderMessage = new OrderMessage()
                    {
                        ID          = order.ID,
                        OrderUserID = order.OrderUserID,
                        OrderTime   = order.OrderTime,
                        OrderItems  = null,
                        MessageTime = DateTime.Now,
                        ProductID   = order.ProductID // For demo use
                    };

                    await CapPublisher.PublishAsync(EventConstants.EVENT_NAME_CREATE_ORDER, orderMessage, trans);

                    trans.Commit();
                }
            }

            return(true);
        }
Example #10
0
        private async Task <bool> UpdateStorageNumberAsync(OrderMessage order)
        {
            Console.Out.WriteLineAsync($"[StorageService] StorageNumber - 1");
            return(true);
            //using (var conn = new SqlConnection(_connStr))
            //{
            //    string sqlCommand = @"UPDATE [dbo].[Storages] SET StorageNumber = StorageNumber - 1
            //                                                    WHERE StorageID = @ProductID";

            //    int count = await conn.ExecuteAsync(sqlCommand, param: new
            //    {
            //        ProductID = order.ProductID
            //    });

            //    return count > 0;
            //}
        }
Example #11
0
        public async Task PersistOrderToDatabase(string salesChannel, int salesChannelId)
        {
            OrderMessage orderMessage = new OrderMessage
            {
                SalesChannel = salesChannel
            };
            var backOfficeOrder = new BackOfficeOrder();

            _salesChannelIdQueryMock.Setup(p => p.GetIdBy(salesChannel))
            .ReturnsAsync(salesChannelId);
            _backOfficeOrderFactoryMock.Setup(p => p.InstantiateFrom(orderMessage, salesChannelId))
            .Returns(backOfficeOrder);

            await _orderStreamSyncer.Sync(orderMessage);

            _orderPersisterMock.Verify(p => p.Persist(backOfficeOrder));
        }
        public void Publish(string text = "lalala")
        {
            // TODO: Does Inventory need to publish at all? Or just listen for messages?

            // optional: use model to create a message
            var message = new OrderMessage
            {
                Text = text
            };

            // But in the end you will need a string
            string payload = JsonConvert.SerializeObject(message);

            // Example for Order microservice
            var exchangeName = Environment.GetEnvironmentVariable("ORDERS_EXCHANGE");

            publisher.Publish(exchangeName, payload);
        }
        public async Task <IActionResult> PostAsync([FromBody] OrderDto dto)
        {
            var message = new OrderMessage
            {
                id              = 1,
                orderId         = dto.orderId,
                createOrderTime = DateTime.Now,
                state           = "未支付",
                total           = 123.59M,
                userId          = 10001
            };

            //发订单信息到消息队列
            //bus.Publish(message);
            await bus.PublishAsync(message, "Topic.EmailServer");

            return(Ok("order insert success"));
        }
 public void Visit(IVisitable pVisitable)
 {
     if (pVisitable is Order)
     {
         Order lOrder = pVisitable as Order;
         Result = new OrderMessage()
         {
             OrderGuid            = lOrder.OrderNumber,
             FromAccountNumber    = mFromAccountNumber,
             ToAccountNumber      = mToAccountNumber,
             CustomerEmailAddress = lOrder.Customer.Email,
             DestinationAddress   = lOrder.Customer.Address,
             SourceAddress        = "Video Store Address",
             Total = lOrder.Total ?? 0,
             Topic = "videostore"
         };
     }
 }
Example #15
0
        public void Ctor_ShouldAllowNullSubject()
        {
            var now          = DateTime.Now;
            var orderMessage = new OrderMessage
            {
                Body     = "Hello world",
                DateSent = now,
                From     = "Foo",
                To       = "Bar",
                Subject  = null
            };

            Assert.AreEqual("Hello world", orderMessage.Body);
            Assert.AreEqual("Foo", orderMessage.From);
            Assert.AreEqual("Bar", orderMessage.To);
            Assert.IsTrue(DateTime.Now >= now);
            Assert.IsNull(orderMessage.Subject);
        }
Example #16
0
        private void MessageReceived(object s, MessageReceivedEventArgs e)
        {
            OrderMessage message = null;

            try
            {
                message = JsonConvert.DeserializeObject <OrderMessage>(e.Message);
            }
            catch (Exception ex)
            {
                ErrorOccured(this, ex.Message);
            }

            if (message != null && message.Ok && message.Order != null && OrderReceived != null)
            {
                OrderReceived(this, message.Order);
            }
        }
Example #17
0
        private async Task <bool> AddDeliveryRecordAsync(OrderMessage order)
        {
            using (var conn = new SqlConnection(_connStr))
            {
                string sql   = @"INSERT INTO [dbo].[Deliveries] (DeliveryID, OrderID, OrderUserID, CreatedTime,UpdatedTime)
                                                            VALUES (@DeliveryID, @OrderID, @OrderUserID, @CreatedTime,@UpdatedTime)";
                int    count = await conn.ExecuteAsync(sql, new
                {
                    DeliveryID  = Guid.NewGuid().ToString(),
                    OrderID     = order.ID,
                    OrderUserID = order.OrderUserID,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now
                });

                return(count > 0);
            }
        }
Example #18
0
        /// <summary>
        /// Called when Order Execution is received
        /// </summary>
        /// <param name="execution">TradeHub Execution</param>
        public override void OnExecutionArrived(Execution execution)
        {
            try
            {
                ConsoleWriter.WriteLine(ConsoleColor.Green, "Order Execution received : " + execution);

                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Order Execution received : " + execution, _type.FullName, "OnExecutionArrived");
                }

                // Resart trading algo on full fill
                if (execution.Fill.LeavesQuantity.Equals(0))
                {
                    if (_entryOrderSent)
                    {
                        _entryOrderSent = false;

                        // Get new unique ID
                        var id = (_orderId++).ToString("X");

                        Security security = new Security {
                            Symbol = execution.Order.Security.Symbol
                        };

                        var orderSide = execution.Fill.ExecutionSide.Equals(TradeHubConstants.OrderSide.BUY)
                            ? TradeHubConstants.OrderSide.SELL
                            : TradeHubConstants.OrderSide.BUY;

                        // Create Market Order
                        MarketOrder marketOrder = OrderMessage.GenerateMarketOrder(id, security, orderSide, 10,
                                                                                   _orderExecutionProvider);

                        // Send Market Order
                        SendOrder(marketOrder);
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "OnExecutionArrived");
            }
        }
Example #19
0
        static async Task <HttpResponseMessage> SendPost(OrderMessage message, CancellationToken cancellationToken)
        {
            endpoint = "http://localhost:63942/Pedido/{id}/entregue";

            endpoint = endpoint.Replace("{id}", message.Rastreio.IdPedido);

            using (var client = new HttpClient())
                using (var request = new HttpRequestMessage(HttpMethod.Put, endpoint))
                    using (var httpContent = CreateHttpContent(message))
                    {
                        request.Content = httpContent;
                        request.Headers.Add("Authorization", token);

                        using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
                        {
                            return(response);
                        }
                    }
        }
 private void ProcessOrderMessage(string portfolioName, OrderMessage message)
 {
     if (OwnInnerAdapter)
     {
         if (portfolioName == Extensions.SimulatorPortfolioName)
         {
             _emuOrderIds.Add(message.TransactionId);
             SendToEmulator(message);
         }
         else
         {
             base.OnSendInMessage(message);
         }
     }
     else
     {
         _emuOrderIds.Add(message.TransactionId);
         SendToEmulator(message);
     }
 }
        private async Task <bool> AddDeliveryRecordAsync(OrderMessage order)
        {
            //throw new Exception("test"); // just for demo use
            using (var conn = new SqlConnection(_connStr))
            {
                string sqlCommand = @"INSERT INTO [dbo].[Deliveries] (DeliveryID, OrderID, ProductID, OrderUserID, CreatedTime)
                                                            VALUES (@DeliveryID, @OrderID, @ProductID, @OrderUserID, @CreatedTime)";

                int count = await conn.ExecuteAsync(sqlCommand, param : new
                {
                    DeliveryID  = Guid.NewGuid().ToString(),
                    OrderID     = order.ID,
                    OrderUserID = order.OrderUserID,
                    ProductID   = order.ProductID,
                    CreatedTime = DateTime.Now
                });

                return(count > 0);
            }
        }
 protected OrderBase(OrderMessage message, Symbol symbol)
 {
     ClientId      = DWConverter.FromProtoUuid(message.OrderClientId);
     TimeStamp     = DWConverter.FromLongDateTime(message.OrderTimestamp);
     Type          = message.OrderType;
     Side          = message.Side;
     Leverage      = message.Leverage;
     Duration      = message.Duration;
     Price         = DWConverter.FromProtoDecimal(message.Price);
     Quantity      = DWConverter.FromProtoDecimal(message.Quantity);
     PaidPrice     = DWConverter.FromProtoDecimal(message.PaidPrice);
     status        = null;
     TargetSymbol  = symbol;
     ContractId    = message.ContractId;
     OldClientId   = DWConverter.FromProtoUuid(message.OldClientId);
     OpenTime      = DWConverter.FromLongDateTime(message.OpenTime);
     OrderTraderId = message.OrderTraderId;
     OrigClientId  = DWConverter.FromProtoUuid(message.OrigClientId);
     OrigQuantity  = DWConverter.FromProtoDecimal(message.OrigQuantity);
 }
Example #23
0
        public override Google.ProtocolBuffers.IMessage ToMessage(string session_id)
        {
            string request_id = Guid.NewGuid().ToString();
            string timestamp  = com.quantmodel.common.network.message.ClientMessage.getTimestamp();

            return
                (ClientAdapterRequest.CreateBuilder()
                 .SetRequestId(request_id)
                 .SetSessionId(session_id)
                 .SetTimestamp(timestamp)
                 .SetType(ClientAdapterRequest.Types.RequestType.DEALING)
                 .SetDealingRequest(
                     DealingEngineRequest.CreateBuilder()
                     .SetRequestId(request_id)
                     .SetTimestamp(timestamp)
                     .SetType(DealingEngineRequest.Types.RequestType.RELEASE_ORDER)
                     .SetOrder(OrderMessage.CreateBuilder()
                               .SetOrderData(OrderData.CreateBuilder()
                                             .SetOrderId(order_id))))
                 .Build());
        }
Example #24
0
        public static void Produce(OrderMessage message)
        {
            var config = new ProducerConfig
            {
                BootstrapServers = Server
            };

            Action <DeliveryReport <string, OrderMessage> > handler = r =>
                                                                      Console.WriteLine(!r.Error.IsError
                    ? $"Delivered message to {r.TopicPartitionOffset} on topic {r.TopicPartition}"
                    : $"Delivery Error: {r.Error.Reason}");

            using var p = new ProducerBuilder <string, OrderMessage>(config).SetValueSerializer(new Serializer <OrderMessage>()).Build();
            p.Produce(
                message.Topic,
                new Message <string, OrderMessage> {
                Key = message.Id, Value = message
            },
                handler);
            p.Flush(TimeSpan.FromSeconds(10));
        }
Example #25
0
        public static async Task PublishNotification(OrderMessage order)
        {
            // --> fanout!
            var products = s_repository.GetProducts();
            var relevant = order.ProductIds;
            var numbers  = products.Where(y => relevant.Any(n => n == y.Id))
                           .Select(x => x.ArticleNumber);

            var notify = new NotifySupplier
            {
                CustomerId     = order.CustomerId,
                SupplierId     = order.SupplierId,
                ProductNumbers = numbers.ToArray()
            };

            var       advanced            = s_Bus.Advanced;
            IExchange ex                  = advanced.ExchangeDeclare("notifications", "fanout", passive: true);
            IMessage <NotifySupplier> msg = new PushOrder(notify);

            await advanced.PublishAsync(ex, "", mandatory : true, message : msg);
        }
        /// <summary>
        /// 当消息消费异常,会发现,CAP会自动帮忙重试
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        private async Task <bool> AddDeliveryRecordAsync(OrderMessage order)
        {
            //throw new Exception("test"); // just for demo use
            using (var conn = new MySqlConnection(DeliveryDbContext.ConnectionString))
            {
                string sqlCommand = @"insert into deliveries(deliveryid, orderid, orderuserid, createdtime, updatedtime) 
values (@deliveryid, @orderid, @orderuserid, @createdtime, @updatedtime)";

                int count = await conn.ExecuteAsync(sqlCommand, param : new
                {
                    DeliveryID  = Guid.NewGuid().ToString(),
                    OrderID     = order.ID,
                    OrderUserID = order.OrderUserID,
                    ProductID   = order.ProductID,
                    CreatedTime = DateTime.Now,
                    updatedtime = DateTime.Now
                });

                return(count > 0);
            }
        }
        public void SendLimitOrderAndCancelItEnsureItGetsCancelled()
        {
            bool       cancellationArrived = false;
            Order      cancelledOrder      = null;
            LimitOrder limitOrder          = OrderMessage.GenerateLimitOrder(new Security()
            {
                Symbol = "MSFT"
            }, OrderSide.BUY, 1,
                                                                             10, "Tradier");

            limitOrder.OrderTif = OrderTif.DAY;
            _executionProvider.SendLimitOrder(limitOrder);
            _executionProvider.CancellationArrived += delegate(Order order)
            {
                cancellationArrived = true;
                cancelledOrder      = order;
            };
            _executionProvider.CancelLimitOrder(limitOrder);
            Assert.True(cancellationArrived);
            Assert.AreEqual(cancelledOrder.OrderID, limitOrder.OrderID);
        }
Example #28
0
        private async Task QueueOrderAsync(string confirmationId, OrderRequest order)
        {
            var orderMessage = new OrderMessage
            {
                ConfirmationId = confirmationId,
                Amount         = order.Amount,
                CustomerName   = order.CustomerName,
                ProductId      = order.ProductId
            };

            var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(orderMessage)))
            {
                ContentType   = "application/json",
                CorrelationId = Guid.NewGuid().ToString()
            };

            var connectionString = Environment.GetEnvironmentVariable("ServiceBus_ConnectionString");
            var queueName        = Environment.GetEnvironmentVariable("Orders_Queue_Name");
            var queueClient      = new QueueClient(connectionString, queueName);
            await queueClient.SendAsync(message);
        }
        static async Task RunLoop(IEndpointInstance endpointInstance)
        {
            while (true)
            {
                _logger.Info("Press 'P' to place an order, or 'Q' to quit.");

                var key = Console.ReadKey();
                Console.WriteLine();

                switch (key.Key)
                {
                case ConsoleKey.P:

                    // Instantiate an order
                    var order = new OrderMessage()
                    {
                        OrderId     = Guid.NewGuid().ToString(),
                        OrderStatus = 2,
                        OrderDate   = new DateTime(2017, 03, 09),
                        Customer    = new OrderMessageCustomer
                        {
                            FirstName = "Abderrahman",
                            LastName  = "Cheddir"
                        }
                    };

                    _logger.Info($"Sending order, OrderId = {order.OrderId}");
                    await endpointInstance.Send(order).ConfigureAwait(false);

                    break;

                case ConsoleKey.Q:
                    return;

                default:
                    _logger.Info("Unknown input. Please try again.");
                    break;
                }
            }
        }
Example #30
0
        /// <summary>
        /// Sends enrty order to the Order Execution Service
        /// </summary>
        /// <param name="orderSide">Order side on which to open position</param>
        /// <param name="symbol">Symbol on which to send order</param>
        private void SendBlackwoodEntryOrder(string orderSide, string symbol)
        {
            try
            {
                if (!orderSide.Equals(TradeHubConstants.OrderSide.NONE))
                {
                    _entryOrderSent = true;

                    ConsoleWriter.WriteLine(ConsoleColor.Green, "Sending" + orderSide + " entry order.");

                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Sending" + orderSide + " entry order.", _type.FullName, "SendEntryOrder");
                    }

                    // Get new unique ID
                    var id = (_orderId++).ToString("X");

                    Security security = new Security {
                        Symbol = symbol
                    };

                    // Create new Limit Order
                    MarketOrder marketOrder = OrderMessage.GenerateMarketOrder(id, security, TradeHubConstants.OrderSide.SHORT, 100, _orderExecutionProvider);

                    // Set OPG Venue
                    marketOrder.Exchange = "SDOT";
                    // Set Order TIME_OUT
                    marketOrder.OrderTif = TradeHubConstants.OrderTif.DAY;

                    // Send Market Order to OEE
                    SendOrder(marketOrder);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "SendEntryOrder");
            }
        }
Example #31
0
 private void putOrderButton_Click(object sender, EventArgs e)
 {
     OrderMessage newOrder = new OrderMessage();
     newOrder.Currency = this.currencyTextBox.Text;
     newOrder.DeliveryDate = this.deliveryDateTimePicker.Value;
     newOrder.ItemDescription = this.itemDescriptionTextBox.Text;
     newOrder.ItemNumber = this.itemNumberTextBox.Text;
     newOrder.OrderDate = this.orderDateTimePicker.Value;
     newOrder.Price = int.Parse(this.priceTextBox.Text);
     newOrder.Quantity = int.Parse(this.quantityTextBox.Text);
     newOrder.Recipient = this.recipientTextBox.Text;
     newOrder.Sender = this.senderTextBox.Text;
     newOrder.Text = this.textTextBox.Text;
     OrderServiceClient proxy = new OrderServiceClient();
     proxy.ClientCredentials.UserName.UserName = "******";
     proxy.ClientCredentials.UserName.Password = "******";
     bool success = proxy.PutOrder(newOrder);
     if (success)
         MessageBox.Show("PutOrder() call was successful.");
     else
         MessageBox.Show("PutOrder() call failed.");
 }
Example #32
0
        public void sendOrder(Guid clientId, double latitude, double longitude)
        {
            OrderMessage orderMessage = new OrderMessage();

            orderMessage.clientId   = clientId;
            orderMessage.timestamp  = DateTime.UtcNow;
            orderMessage.expiration = DateTime.UtcNow.AddMinutes(1);
            orderMessage.location   = new GeoData()
            {
                latitude = latitude, longitude = longitude
            };
            string json = JsonSerializer.Serialize(orderMessage);

            using (var producer = new ProducerBuilder <Null, string>(config).Build())
            {
                producer.Produce(orderTopic, new Message <Null, string> {
                    Value = json
                });
                producer.Flush();
            }
            Console.WriteLine("Order sent");
        }
Example #33
0
        public async Task <bool> CreateOrderByDapper(IOrder order)
        {
            using (var conn = new SqlConnection(ConnStr))
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    // business code here
                    string sqlCommand = @"INSERT INTO [dbo].[Orders](OrderID, OrderTime, OrderUserID, ProductID)
                                                                VALUES(@OrderID, @OrderTime, @OrderUserID, @ProductID)";

                    order.ID = GenerateOrderID();
                    await conn.ExecuteAsync(sqlCommand, param : new
                    {
                        OrderID     = order.ID,
                        OrderTime   = DateTime.Now,
                        OrderUserID = order.OrderUserID,
                        ProductID   = order.ProductID
                    }, transaction : trans);

                    // For Dapper/ADO.NET, need to pass transaction
                    var orderMessage = new OrderMessage()
                    {
                        ID          = order.ID,
                        OrderUserID = order.OrderUserID,
                        OrderTime   = order.OrderTime,
                        OrderItems  = null,
                        MessageTime = DateTime.Now,
                        ProductID   = order.ProductID // For demo use
                    };

                    await CapPublisher.PublishAsync(EventConstants.EVENT_NAME_CREATE_ORDER, orderMessage, trans);

                    trans.Commit();
                }
            }

            return(true);
        }
 public void should_notify_order_received_when_mail_arrives()
 {
     var mailMessage = new OrderMessage();
     _mailTranslator.Process(mailMessage);
     _orderListener.AssertWasCalled(l=>l.OrderReceived(Arg<string>.Is.Anything));
 }