Ejemplo n.º 1
0
        public ClientOrderStatisticalDTO GetClientOrdersStatistics(OrderCommand cmd, int userId, ref int pagesCount)
        {
            var user    = new UserDalFacade().GetAccountUser(userId);
            var isAdmin = user.isSunnat || user.PositionRole == 1;

            return(new OrderDalFacade().GetClientOrdersStats(cmd, user.WorkPlace.Id.Value, isAdmin, ref pagesCount));
        }
Ejemplo n.º 2
0
        private void btn_Click(object sender, EventArgs e)
        {
            Button       btn     = sender as Button;
            OrderCommand command = (OrderCommand)Enum.Parse(typeof(OrderCommand), btn.ID, true);

            ProcOrder(command);
        }
Ejemplo n.º 3
0
 private Order BindItem(OrderCommand order)
 {
     return(new Order
     {
         Customer = new Customer
         {
             CustomerId = order.CustomerId
         },
         Restaurant = new Restaurant
         {
             RestaurantId = order.RestaurantId
         },
         Amount = order.Amount,
         Quantity = order.Quantity,
         Status = 0,
         TransactionId = order.TransactionId,
         Items = order.Items.Select(x => new OrderItems
         {
             Amount = x.Amount,
             Quantity = x.Quantity,
             Meal = new Meal
             {
                 MealId = x.MealId
             }
         })
     });
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Invokes a commands on the <c>Machine</c> instance
        /// </summary>
        /// <param name="commandType">One of the <c>Command</c> enum</param>
        /// <param name="commandInput">Dynamic Input recieved from MachineClient.
        /// Manager must cast it to the type the command requires, trusting the validations in client to filter out incorrect command parameters entered by user</param>
        public void ExecuteCommand(Command commandType, object commandInput)
        {
            IMachineCommand machineCommand;

            switch (commandType)
            {
            case Command.InsertMoney:
                machineCommand = new InsertMoneyCommand((int)commandInput);
                break;

            case Command.Order:
                machineCommand = new OrderCommand((string)commandInput);
                break;

            case Command.SmsOrder:
                machineCommand = new SmsOrderCommand((string)commandInput);
                break;

            case Command.Recall:
                machineCommand = new RecallCommand();
                break;

            default: return;        //No command will be executed
            }
            _machine = machineCommand.Execute(_machine);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write("Creating topics and subscriptions ... ");

            //create predefined topics for the sample application
            InfrastructureManagement.CreateTopics();

            Console.WriteLine("Done!");
            Console.ResetColor();

            WaitForEnter("Press enter to send the messages");

            //place orders
            var command = new OrderCommand();

            command.PlaceOrders();

            WaitForEnter("Press enter to receive messages");

            var orderSubscriptionQuery = new OrderSubscriptionQuery();

            orderSubscriptionQuery.ReceiveOrder();

            WaitForEnter("Press any key to continue");
        }
Ejemplo n.º 6
0
        public void CanOrderOrderedDocuments()
        {
            var path = Path.GetFullPath(@"data\ordered-documents\");

            var command = new LoadDocumentsCommand();

            command.Author             = new Author();
            command.DocumentsPath      = path;
            command.OutputRootPath     = Path.GetFullPath("output");
            command.RenderedExtensions = new[] { "md" };
            command.RootUrl            = "http://www.example.com/";
            command.ApplicationUrl     = "/foo";
            command.ExecuteAsync().Wait();

            var order = new OrderCommand();

            order.Documents = command.Documents;
            order.Execute();

            Assert.Equal(1, order.Books.Count());

            var doc = command.Documents.Skip(3).Take(1).Single();

            var data = order.Books.First().GetAsDynamic(doc);
        }
Ejemplo n.º 7
0
        //[Fact]
        public async Task Send()
        {
            var command = new OrderCommand();
            var order   = await this._mediator.SendAsync <Order>(command);

            this.WriteLine(order);
        }
Ejemplo n.º 8
0
        public IActionResult Post([FromBody] OrderCommand order)
        {
            try
            {
                return(Ok(orderService.Insert(order)));
            } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); }

            return(BadRequest("Order was not registered"));
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            var port = int.Parse(Configuration["service:port"]);

            var brokerList = Configuration["kafkaclient:brokerlist"];
            var config     = new Dictionary <string, object>
            {
                { "group.id", "order-command" },
                { "enable.auto.commit", "false" },
                { "bootstrap.servers", brokerList }
            };

            IEventEmitter kafkaEmitter = new KafkaEventEmitter(config, loggerFactory.CreateLogger <KafkaEventEmitter>());
            // TODO: this channel needs to use a service-discovery hostname
            var orderChannel = new Channel($"{Configuration["orderclient:hostname"]}:{Configuration["orderclient:port"]}",
                                           ChannelCredentials.Insecure);
            var inventoryChannel = new Channel($"{Configuration["inventoryclient:hostname"]}:{Configuration["inventoryclient:port"]}",
                                               ChannelCredentials.Insecure);

            logger.LogInformation($"Configured gRPC channel for Order Management client: {orderChannel.ResolvedTarget}");
            logger.LogInformation($"Configured gRPC channel for Inventory Management client: {inventoryChannel.ResolvedTarget}");

            var orderClient     = new OrderManagement.OrderManagementClient(orderChannel);
            var inventoryClient = new InventoryManagement.InventoryManagementClient(inventoryChannel);

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, OrderCommand.Descriptor);

            var rpcLogger = loggerFactory.CreateLogger <OrderCommandImpl>();
            var server    = new Server
            {
                Services = { OrderCommand.BindService(new OrderCommandImpl(rpcLogger, kafkaEmitter, orderClient, inventoryClient)),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();

            logger.LogInformation("Orders Command gRPC Service Listening on Port " + port);

            // Keep the process alive without consuming CPU cycles
            mre.WaitOne();
        }
Ejemplo n.º 10
0
        private void Order(Site site)
        {
            using (var capture = Statistics.Current.Start(StatisticTiming.Ordering))
            {
                var order = new OrderCommand();
                order.Documents = site.Documents;
                order.Execute();

                site.Books = order.Books;
            }
        }
 public Order Map(OrderCommand order)
 {
     return(new Order()
     {
         Id = order.Id,
         OrderDate = order.OrderDate,
         Price = order.Price,
         Quantity = order.Quantity,
         CustomerId = order.CustomerId
     });
 }
Ejemplo n.º 12
0
 public void SetOrder(OrderCommand order)
 {
     if (order.ToString() == "BakeChickenWingCommand")
     {
         Console.WriteLine("鸡翅没有了,换点别的吧");
     }
     else
     {
         Console.WriteLine($"{order} 下单成功");
         _orders.Add(order);
     }
 }
Ejemplo n.º 13
0
 public IActionResult Post([FromBody] OrderCommand command)
 {
     try
     {
         _orderAppService.Add_a_new_Order_and_Order_Item_for_an_existing_Customer(command);
         return(Ok("Customer added with success."));
     }
     catch (System.Exception ex)
     {
         return(Problem(ex.Message));
     }
 }
Ejemplo n.º 14
0
        public async Task <ActionResult <RegBookResponseObj> > CheckInBook([FromBody] OrderObj requestObj)
        {
            OrderCommand command  = _mapper.Map <OrderCommand>(requestObj);
            var          response = await _mediator.Send(command);

            if (response.OrderId < 1 || !response.Status.IsSuccessful)
            {
                return(BadRequest(response));
            }
            var locatioUri = _uriService.GetBookUri(response.OrderId.ToString());

            return(Created(locatioUri, response));
        }
Ejemplo n.º 15
0
        public Order Insert(OrderCommand order)
        {
            var _order = BindItem(order);

            _order = repository.Insert(_order);

            foreach (var item in order.Items)
            {
                item.OrderId = _order.OrderId;
                repository.InsertItem(BindOrderItem(item));
            }

            return(GetById(_order.OrderId));
        }
Ejemplo n.º 16
0
        public ActionResult Order(OrderCommand order, [FromServices] OrderCommandHandler handler)
        {
            var result = handler.Handle(order);

            if (result.PaymentOk)
            {
                ViewData["Message"] = "Thank you. Your order has been placed.";
                return(View(result));
            }
            else
            {
                return(RedirectToAction("PaymentFailed"));
            }
        }
Ejemplo n.º 17
0
 public void Checkout(CheckoutParameter checkoutParameter)
 {
     foreach (var product in checkoutParameter.CartParameter.Products)
     {
         var orderCommand = new OrderCommand
         {
             CustomerId = checkoutParameter.CustomerId,
             CartId     = checkoutParameter.CartParameter.CartId,
             ProductId  = product.ProductId,
             ItemCount  = product.ItemCount
         };
         _orderCommandHandler.Handle(orderCommand);
     }
 }
Ejemplo n.º 18
0
        public static Command Build(string[] data)
        {
            Command command;

            if (int.TryParse(data[0], out _))
            {
                command = new OrderCommand(data);
            }
            else
            {
                command = new RegisterProductCommand(data);
            }

            return(command);
        }
Ejemplo n.º 19
0
        private void ProcOrder(OrderCommand command)
        {
            using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey))
            {
                OrderFacade facade = new OrderFacade(uow);
                IFacadeUpdateResult <OrderData> result = null;

                switch (command)
                {
                case OrderCommand.Accept:
                    result = facade.OrderAccept(Order.OrderId);
                    break;

                case OrderCommand.Reject:
                    result = facade.OrderReject(Order.OrderId);
                    break;

                case OrderCommand.Delivering:
                    result = facade.OrderDelivering(Order.OrderId);
                    break;

                case OrderCommand.Complete:
                    result = facade.OrderComplete(Order.OrderId);
                    break;

                case OrderCommand.Incomplete:
                    result = facade.OrderIncomplete(Order.OrderId);
                    break;
                }

                if (result.IsSuccessful)
                {
                    // retrieve saved order info
                    // remove this line on May.23, move retrieve action to caller page
                    //Order = facade.RetrieveOrderInfo(Order.OrderId, new OrderInfoConverter());
                    if (OrderChanged != null)
                    {
                        InstanceChangedEventArgs arg = new InstanceChangedEventArgs(Order);
                        OrderChanged(this, arg);
                    }
                }
                else
                {
                    // Deal with Update result
                    //ProcUpdateResult(result.ValidationResult, result.Exception);
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Order(OrderCommand orderCommand)
        {
            return(await
                   // Try to generate an order
                   from maybeOrder in
                   from product in _repository.FindByIdAsync(orderCommand.ProductId)
                   select OrderBehavior.TryOrder(product, orderCommand.Quantity)

                   // Update the DB
                   from result in maybeOrder.AwaitSideEffect(_repository.UpdateAsync)

                   // Return results
                   select result.Match <IActionResult>(
                       Ok,
                       StatusCode(500, new { Error = "No available units." })));
        }
        public TradingSignal(
            Instrument instrument,
            string orderId, OrderCommand command, TradeType tradeType, decimal?price, decimal volume, bool isMarginOrder, DateTime time, OrderType orderType = OrderType.Market)
        {
            Instrument = instrument;

            OrderId = orderId;
            Command = command;

            TradeType     = tradeType;
            Price         = price;
            Volume        = volume;
            Time          = time;
            OrderType     = orderType;
            IsMarginOrder = isMarginOrder;
        }
Ejemplo n.º 22
0
        public TradingSignal(
            Instrument instrument,
            string orderId, OrderCommand command, TradeType tradeType, decimal?price, decimal volume, DateTime time, OrderType orderType = OrderType.Market,
            TimeInForce timeInForce = TimeInForce.FillOrKill)
        {
            Instrument = instrument;

            OrderId = orderId;
            Command = command;

            TradeType   = tradeType;
            Price       = price;
            Volume      = volume;
            Time        = time;
            OrderType   = orderType;
            TimeInForce = timeInForce;
        }
Ejemplo n.º 23
0
        public void ExecuteOrder(OrderCommand orderCommand)
        {
            var productAggregate = _productRepository.Get(orderCommand.ProductId);
            var totalAvailable   = productAggregate.GetTotalAvailable();

            if (totalAvailable < orderCommand.ItemCount)
            {
                PublishOrderFailedEvent(orderCommand);
                return;
            }

            var orderResult = CreateOrders(productAggregate, orderCommand);

            PersistOrderResult(orderResult);
            PublishOrderSucceededEvent(orderCommand);
            UpdateProductAvailability(orderCommand.ProductId, totalAvailable - orderCommand.ItemCount);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 根据下单指令下单。
        /// </summary>
        /// <param name="command">下单指令。</param>
        private bool PlaceOrderForOrderCommand(OrderCommand command)
        {
            string      errorMessage = string.Empty;
            USeOrderNum orderNum     = m_orderDriver.PlaceOrder(command.Instrument, command.OrderQty, command.OrderPrice, command.OffsetType, command.OrderSide, out errorMessage);

            command.OrderNum = orderNum;
            if (orderNum == null)
            {
                Debug.Assert(string.IsNullOrEmpty(errorMessage) == false);
                command.OrderErrorMessage = errorMessage;

                return(false); // 下单失败
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 25
0
        public void TestShoes()
        {
            // Given
            IProduct           shoes      = new Shoes();
            PurchaseController controller = new PurchaseController();
            ICommand           order      = new OrderCommand(shoes);

            controller.InsertCommand(order);
            ICommand buy = new BuyCommand(shoes);

            controller.InsertCommand(buy);

            // When
            var order_t = order.Execute();
            var buy_t   = buy.Execute();

            // Then
            Assert.AreEqual("Shoes", order_t);
            Assert.AreEqual("39.99", buy_t);
        }
Ejemplo n.º 26
0
        public void TestTshirt()
        {
            // Given
            IProduct           tshirt     = new Tshirt();
            PurchaseController controller = new PurchaseController();
            ICommand           order      = new OrderCommand(tshirt);

            controller.InsertCommand(order);
            ICommand buy = new BuyCommand(tshirt);

            controller.InsertCommand(buy);

            // When
            var order_t = order.Execute();
            var buy_t   = buy.Execute();

            // Then
            Assert.AreEqual("T-shirt", order_t);
            Assert.AreEqual("19.99", buy_t);
        }
Ejemplo n.º 27
0
        public void CanOrderUnorderedDocuments()
        {
            var path = Path.GetFullPath(@"data\dated-documents\");

            var command = new LoadDocumentsCommand();

            command.Author             = new Author();
            command.DocumentsPath      = path;
            command.OutputRootPath     = Path.GetFullPath("output");
            command.RenderedExtensions = new[] { "md" };
            command.RootUrl            = "http://www.example.com/";
            command.ApplicationUrl     = "/foo";
            command.ExecuteAsync().Wait();

            var order = new OrderCommand();

            order.Documents = command.Documents;
            order.Execute();

            Assert.Equal(0, order.Books.Count());
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            ILoggerFactory loggerFactory = new LoggerFactory()
                                           .AddConsole()
                                           .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            var port = int.Parse(Configuration["service:port"]);

            IEventEmitter kafkaEmitter = new KafkaEventEmitter();
            // TODO: this channel needs to use a service-discovery hostname
            Channel orderChannel = new Channel($"{Configuration["orderclient:hostname"]}:{Configuration["orderclient:port"]}",
                                               ChannelCredentials.Insecure);

            logger.LogInformation($"Configured gRPC channel for Order Management client: {orderChannel.ResolvedTarget}");
            var orderClient = new OrderManagement.OrderManagementClient(orderChannel);

            Server server = new Server
            {
                Services = { OrderCommand.BindService(new OrderCommandImpl(kafkaEmitter, orderClient)) },
                Ports    = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();

            logger.LogInformation("Orders Command RPC Service Listening on Port " + port);

            // Keep the process alive without consuming CPU cycles
            mre.WaitOne();
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            const int Port = 3000;

            IEventEmitter kafkaEmitter = new KafkaEventEmitter();
            Channel       orderChannel = new Channel("127.0.0.1:3001", ChannelCredentials.Insecure);
            var           orderClient  = new OrderManagement.OrderManagementClient(orderChannel);

            Server server = new Server
            {
                Services = { OrderCommand.BindService(new OrderCommandImpl(kafkaEmitter, orderClient)) },
                Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Orders Command RPC Service Listening on Port " + Port);
            Console.WriteLine("Press any key to stop");

            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
Ejemplo n.º 30
0
        internal IFacadeUpdateResult <OrderData> PerformOrderCommand(object orderId, OrderCommand command)
        {
            ArgumentValidator.IsNotNull("orderId", orderId);

            FacadeUpdateResult <OrderData> result = new FacadeUpdateResult <OrderData>();
            IOrderService service  = UnitOfWork.GetService <IOrderService>();
            Order         instance = RetrieveOrNew <OrderData, Order, IOrderService>(result.ValidationResult, orderId);

            if (result.IsSuccessful)
            {
                ValidateOrderCommand(instance, command, result.ValidationResult);
                if (result.IsSuccessful)
                {
                    instance.StatusId = (int)command;
                    var saveQuery = service.Save(instance);

                    result.AttachResult(instance.RetrieveData <OrderData>());
                    result.Merge(saveQuery);
                }
            }

            return(result);
        }