//function to encode order object to a string public void EncodeOrder(OrderClass order) { lock (this) { string str = order.SenderID + ";" + order.CardNo + ";" + order.Amount + ";" + order.UnitPrice; //send the encoded string to the buffer Program.buffer.setOneCell(str); } }
//function to decode the string to order object public void DecodeOrder(string order) { lock (this) { //split the string to get an array of order information string[] orderArr = order.Split(';'); //create a new object var decodeOrder = new OrderClass() { SenderID = orderArr[0], CardNo = long.Parse(orderArr[1]), Amount = int.Parse(orderArr[2]), UnitPrice = int.Parse(orderArr[3]) }; //process the object and confirm the order Thread orderThread = new Thread(() => OrderProcessing(decodeOrder)); orderThread.Start(); } }
//generate the order information public void OrderProcessing(OrderClass order) { if (order.CardNo >= 5000 && order.CardNo <= 7000) { const double taxRate = 0.08; const double handlingFee = 3; double total = (order.Amount * order.UnitPrice + handlingFee) * (1 + taxRate); //print out order confirm message Console.WriteLine("---- New Order Confirmed ----\n" + "From: Store {0}\n" + "Amount: {1}\n" + "Card Number: {2}\n" + "Chicken Unit Price: {3}\n" + "Total Cost: {4}\n" + "=========================================\n", order.SenderID, order.Amount, order.CardNo, order.UnitPrice, total); } else { Console.WriteLine("Invalid Card Number\n"); } }
//The function to start Retailer threads public void RetailerThread(MultiCellBuffer buffer) { ChickenFarm chicken = new ChickenFarm(); //using loop to keep create the orders while (chicken.GetPrice() != -1) { Thread.Sleep(2000); //double check the price to avoid something happened during the sleep period if (chicken.GetPrice() != -1) { //set random order properties long cardNo = rand.Next(5000, 7000); int amount = rand.Next(1, 5); //add the properties to the object OrderClass newOrder = new OrderClass() { SenderID = Thread.CurrentThread.Name, CardNo = cardNo, Amount = amount, UnitPrice = currPrice }; //print out order created message Console.WriteLine("---- New Order Created ----\n" + "Sender ID: Store {0}\n" + "Card Number: {1}\n" + "Amount of Chickens Ordered: {2}\n" + "Current Unit Price: {3}\n" + "Order Received Time: {4}\n" + "=========================================\n", newOrder.SenderID, newOrder.CardNo, newOrder.Amount, newOrder.UnitPrice, DateTime.Now); //encode the OrderClass object to string EncodeOrder(newOrder); } } }