public static OrderClass getDecodedValue(string encodedString)
        {
            string mergedString = encodedString;//Decrypt(encodedString, "ABCDEFGHIJKLMNOP");
            string[] tokens = mergedString.Split('#');
            OrderClass OrderClass = new OrderClass();

            if (tokens.Length != 5)    // String is not communicated properly
            {
                Console.WriteLine("Parameter missmatch");
                OrderClass.setCreditCardNumber("-1");
                OrderClass.setRoomPrice(-1);
                OrderClass.setNumberOfRooms(-1);
                OrderClass.setSenderID(-1);
                OrderClass.setReceiverID(-1);
            }
            else
            {
                OrderClass.setCreditCardNumber(tokens[0]);
                OrderClass.setRoomPrice(Int32.Parse(tokens[1]));
                OrderClass.setNumberOfRooms(Int32.Parse(tokens[2]));
                OrderClass.setSenderID(Int32.Parse(tokens[3]));
                OrderClass.setReceiverID(Int32.Parse(tokens[4]));
            }

            return OrderClass;
        }
        /*
         * Generate and place orders from TravelAgency Randomly
         */
        public void agency()
        {
            for (int i = 0; i < 2; i++)
            {
                Random random = new Random();
                int r = random.Next(0, 2);

                OrderClass order = new OrderClass();
                order.setCreditCardNumber(TransactionAgency.validCreditCard[random.Next(0, 2)]);
                order.setRoomPrice(price[r]);
                order.setNumberOfRooms(random.Next(1, 5));
                order.setSenderID(tID);
                order.setReceiverID(r);
                string value = EncoderDecoder.getEncodedValue(order);
                lock (this)
                {
                    Monitor.Enter(MainSystem.mcb);
                    try
                    {
                        value = value +"?"+ DateTime.Now.Ticks; //append timestamp to order object
                        MainSystem.mcb.setOneCell(value);
                        Console.WriteLine("\n-----------------------------------------------------------------------");
                        Console.WriteLine("TravelAgency {0}=>\nOrder Details: \n\tRoomPrice:{1} \n\tNumberOfRooms:{2}", order.getSenderID(), order.getRoomPrice(), order.getNumberOfRooms());
                        Console.WriteLine("Order is initiated successfully for Hotel: " + order.getReceiverID());
                        Console.WriteLine("-----------------------------------------------------------------------");
                        MainSystem.placed++;
                    }
                    finally
                    {
                        Monitor.Exit(MainSystem.mcb);
                    }
                }
                Thread.Sleep(600);
            }
        }
        /*The retailer threads are placing their order within this method.
        This class sends the order details to the encoder to encode the message and gets back the encoded message.
        The encoded message is placed within the multicellbuffer from which the server take this request and processes it.*/
        public static void travelFunc()
        {
            try
            {
                while (true)
                {
                    lock (obj)
                    {
                        if (HotelSupplier.prevRoomPrice < HotelSupplier.roomPrice)  //deciding the number of chickens to order based on the old and new price of the chicken.
                            roomNumber = randRoom.Next(30, 60);     //if old chicken price is less than new chicken price then less number of chickens will be ordered.
                        else
                            roomNumber = randRoom.Next(60, 90);

                        Int32 cardNo = randCardNo.Next(5000, 7000);           //random generation of card number
                        OrderClass orderObject = new OrderClass(Thread.CurrentThread.Name, cardNo, roomNumber, DateTime.Now); //creating a object of order class and sending the input parameters
                        string message = Encoder.Encode(orderObject);        //passing the order class object to the encoder decoder class to encode the data
                        MultiCellBuffer.SetOneCell(message);                        //placing the encoded message in the multi cell buffer
                        Console.WriteLine("Order Request being sent..Please Wait");
                        Console.WriteLine("-------------------------------------");
                        Console.WriteLine("{0} requested an order of {1} rooms   \n", Thread.CurrentThread.Name, roomNumber);
                    }
                    Thread.Sleep(3000);         //making the thread to sleep so that all the thread requests are getting processed
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Oops! Error occurred in TravelAgency Function " + e.Message);
            }
        }
        public static string getEncodedValue(OrderClass OrderClass)
        {
            // Create the concatenated string i.e. encoded string
            string encodedString = OrderClass.getCreditCardNumber() + "#" + OrderClass.getRoomPrice() + "#" + OrderClass.getNumberOfRooms() + "#" + OrderClass.getSenderID() + "#" + OrderClass.getReceiverID();

            return encodedString ;
        }
Esempio n. 5
0
        /// <summary>
        /// Utilizes XmlSerializer to encode the OrderClass into a string.
        /// </summary>
        /// <param name="order">OrderClass created by the TravelAgency</param>
        /// <returns>String representation of the Order from the Travel Agency</returns>
        public static string EncodeOrder(OrderClass order)
        {
            XmlSerializer serializer = new XmlSerializer(order.GetType());

            using (StringWriter sw = new StringWriter())
            {
                serializer.Serialize(sw, order);
                return(sw.ToString());
            }
        }
        public void placeOrderUsingTravelAgencyThread(HotelSupplier hs)
        {
            Random rand = new Random();

            this.amount = rand.Next(1, 500 - hs.Price);

            OrderClass o             = new OrderClass(this.senderId, this.cardNo, hs.ReceiverId, this.amount, hs.Price, DateTime.Now.ToString());
            String     encodedString = Encoder.encode(o, Program.key);

            // put this string into buffer
            Program.mcb.setOneCell(encodedString);
        }
Esempio n. 7
0
        public static void receiveOrder()
        {
            while (Program.mcb.totalReads < (Program.noOfPriceCutEvents * Program.taCount * Program.hsCount))
            {
                String     orderStr = Program.mcb.getOneCell();
                OrderClass order    = Decoder.decode(orderStr, Program.key);
                Thread     thread   = new Thread(() => Program.hs[order.ReceiverId - 1].OrderProcessing(order));
                thread.Start();
            }

            Console.WriteLine("*** ThreadALERT : Stopping Dispatcher Thread");
        }
Esempio n. 8
0
 // Call this when you receive order from Multicell Buffer
 public void OrderProcessing(OrderClass obj)
 {
     Console.WriteLine("Hotel Supplier " + this.receiverId + " is processing Order");
     if (obj.CardNo < 5000 && obj.CardNo > 7000)
     {
         Console.WriteLine("Invalid card number bailing out");
     }
     else
     {
         double totalcost = obj.UnitPriceOfRoom * obj.Amount + this.tax + this.locationCharge;
         //send confirmation to Travel Agency
         Console.WriteLine("Order Processed by Hotel Supplier :" + this.receiverId + " for Travel Agency: " + obj.SenderId + " TotalPrice:" + totalcost + " UnitsBooked:" + obj.Amount);
         Program.ta[obj.SenderId - 1].receiveConfirmation(obj);
     }
 }
        /// <summary>
        /// Called once the TravelAgency thread has come back from sleeping. Orders BASE_ROOM_ORDER rooms.
        /// </summary>
        /// <param name="hotelId">Receiver ID for the Hotel</param>
        private void CreateBaseOrder(string hotelId)
        {
            Console.WriteLine("CREATING: Base Order ({0})", Thread.CurrentThread.Name);

            // Tell system no order is needed
            roomsNeeded = false;
            OrderClass order = new OrderClass();

            order.Amount     = BASE_ROOM_ORDER;
            order.CardNo     = CC_NUMS[random.Next(0, CC_NUMS.Length)];
            order.SenderId   = Thread.CurrentThread.Name;
            order.ReceiverId = hotelId;

            Program.mb.setOneCell(Encoder.EncodeOrder(order));
        }
Esempio n. 10
0
 public void receiveTime(OrderClass orderObj, Double amountOfCharge)
 {
     orderObj.setReceiveTime(DateTime.Now);
     Console.WriteLine();
     Console.WriteLine("Order ID: {0}, Agency ID: {1}, UnitPrice of Room: {2}, Amount of Room: {3}, Amount of Charge: {4}, Start Time: {5}, Completed Time: {6}, Time to process the order: {7}", orderObj.getOrderId(), orderObj.getSenderId() + 1, orderObj.getUnitPrice().ToString("f0"), orderObj.getAmt(), amountOfCharge.ToString("f0"), orderObj.getSenderTime(), orderObj.getReceiveTime(), (orderObj.getReceiveTime() - orderObj.getSenderTime()));
     pricecutLockCounter++;
     if (pricecutLockCounter == 10)
     {
         pricecutLock.Event.Set();
         pricecutLockCounter = 0;
         //            Console.WriteLine("Order ID: {0}, Agency ID: {1}, Unit Price: {3}, Amount of Room: {2}, Amount of Charge: {4}, Start Time: {5}, Completed Time: {6}, Time to process the order: {7}", orderObj.getOrderId(), orderObj.getSenderId() + 1, orderObj.getAmt(), roomPrice.price, amountOfCharge, orderObj.getSenderTime(), orderObj.getReceiveTime(), (orderObj.getReceiveTime() - orderObj.getSenderTime()));
         //            if (orderObj.getPriceCutId()<10)
         //                Console.WriteLine("No.{8} Price-cut, Order ID: {0}, Agency ID: {1}, Unit Price: {3}, Amount of Room: {2}, Amount of Charge: {4}, Start Time: {5}, Completed Time: {6}, Time to process the order: {7}", orderObj.getOrderId(), orderObj.getSenderId() + 1, orderObj.getAmt(), roomPrice.price, amountOfCharge, orderObj.getSenderTime(), orderObj.getReceiveTime(), (orderObj.getReceiveTime() - orderObj.getSenderTime()), orderObj.getPriceCutId() + 1);
     }
 }
        public static void orderProcessing(OrderClass order, int price, String timeStamp)
        {
            string decryptedCreditCard = HotelSupplier.client.Decrypt(order.getCreditCardNumber().ToString());
            if (TransactionAgency.checkForValidity(decryptedCreditCard))
            {
                        if (bStatus != null)
                            bStatus(true, order, timeStamp);
                        return;
            }
            else
                Console.WriteLine("Card is not valid");

            bStatus(false, order, timeStamp);
            return;
        }
        /*This method displays the order receipt to the retailer with all the details of the order.
         * It also displays the time taken to process a particular order*/
        public static void orderConfirmation(OrderClass orderObject)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.DarkMagenta;

                Console.WriteLine("Order Receipt being generated.. \n");
                Console.WriteLine("----------------------------------");
                Console.ResetColor();
                Console.WriteLine("Time taken for the order to be processed  = {0} seconds\n", System.Math.Round((DateTime.Now - orderObject.orderStartTime).TotalSeconds, 2)); //calculating the time taken for each order and displaying it
            }
            catch (Exception e)
            {
                Console.WriteLine("Oops! Error occurred during order confirmation " + e.Message);
            }
        }
 public static string Encode(OrderClass orderObject)
 {
     try
     {
         lock (encodeLock)
         {
             String message = orderObject.GetSenderId().ToString() + "#" + orderObject.GetCardNo().ToString() + "#" + orderObject.GetAmount().ToString() + "#" + orderObject.orderStartTime.ToString();  //separating each entity by @ symbol so that when we decode it back it helps to separate the entities.
             byte[] encodebytes = ASCIIEncoding.ASCII.GetBytes(message);
             return Convert.ToBase64String(encodebytes);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return String.Empty;
     }
 }
Esempio n. 14
0
 /// <summary>
 /// Create a new thread to process the order.
 /// </summary>
 /// <param name="order">Order from the TravelAgency threads</param>
 private void ProcessOrder(OrderClass order)
 {
     // Make sure the order is for the current HotelSupplier
     if (order.ReceiverId == Thread.CurrentThread.Name || order.ReceiverId == null)
     {
         Console.WriteLine("RECEIVING: Order for Hotel Supplier ({0})", Thread.CurrentThread.Name);
         OrderProcessing processor        = new OrderProcessing(order, currentPrice);
         Thread          processingThread = new Thread(new ThreadStart(processor.ProcessOrder));
         processingThreads.Add(processingThread);
         processingThread.Name = "Processor_" + Thread.CurrentThread.Name;
         processingThread.Start();
     }
     else
     {
         Console.WriteLine("SKIPPING: Order not for Hotel Supplier ({0})", Thread.CurrentThread.Name);
     }
 }
Esempio n. 15
0
 public static String encoder(OrderClass order)
 {
     if (order != null)
     {
         String orderId      = order.getOrderId().ToString() + "&";
         String senderId     = order.getSenderId().ToString() + "#";
         String cardNo       = order.getCardNo().ToString() + "$";
         String unitPrice    = order.getUnitPrice().ToString() + "?";
         String amountOfRoom = order.getAmt().ToString() + "%";
         String senderTime   = order.getSenderTime().ToString() + "@";
         String str          = orderId + senderId + cardNo + unitPrice + amountOfRoom + senderTime;
         HotelBookingSystem.CryptService.ServiceClient encrypt = new HotelBookingSystem.CryptService.ServiceClient();
         //               Console.WriteLine("string: {0}, encoded: {1}", order, encrypt.Encrypt(str));
         return(encrypt.Encrypt(str));
     }
     else
     {
         return("Null order!");
     }
 }
 /*
  * This event handler checks the order status
  */
 public void RoomStatus(Boolean success, OrderClass oObject, String timeStamp)
 {
     DateTime dt1 = new DateTime(Convert.ToInt64(timeStamp));
     DateTime dt2 = DateTime.Now;
     if (oObject.getSenderID() == tID && success)
     {
         Console.WriteLine("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
         Console.WriteLine("Room Booking is done successfully at HotelID:{0}", oObject.getReceiverID());
         Console.WriteLine("Order Details: \n\tTravelAgency:{0} \n\tRoomPrice:{1} \n\tNumberOfRooms:{2}", oObject.getSenderID(), oObject.getRoomPrice(), oObject.getNumberOfRooms());
         Console.WriteLine("Total Cost: $" + (oObject.getRoomPrice() * oObject.getNumberOfRooms() + 0.12 * (oObject.getRoomPrice() * oObject.getNumberOfRooms())));
         Console.WriteLine("Time span for completion of the order:" + dt2.Subtract(dt1));
         Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
         MainSystem.notified++;
     }
     if (oObject.getSenderID() == tID && !success)
     {
         Console.WriteLine("\n\t\tRoom not booked at Hotel: " + oObject.getReceiverID());
         Console.WriteLine("\t\tTravelAgency:{0}, UnitPrice:{1}, NumberOfUnit:{2}\n", oObject.getSenderID(), oObject.getRoomPrice(), oObject.getNumberOfRooms());
         MainSystem.notified++;
     }
 }
Esempio n. 17
0
        public void orderProcessing()
        {
            String orderString;

            while (true)
            {
                orderString = Program.mcb.getOneCell();
                OrderClass orderObj = Coder.decoder(orderString);
                Monitor.Enter(roomPrice);
                if (HotelSupplier.checkCreditCardNumber(orderObj.getCardNo()))
                {
                    double amountOfCharge = orderObj.getUnitPrice() * orderObj.getAmt() + taxRate * orderObj.getUnitPrice() * orderObj.getAmt() + locationCharge;
                    orderObj.setReceiveTime(DateTime.Now);
                    if (orderCompleted != null)
                    {
                        orderCompleted(orderObj, amountOfCharge);
                    }
                }
                Monitor.Exit(roomPrice);
            }
        }
 public static void processOrder(OrderClass orderObj, int roomPrice)
 {
     try
     {
         lock (lockObject)
         {
             if (orderObj.GetCardNo() >= 5000 && orderObj.GetCardNo() <= 7000) //checking the card number is valid or not
             {
                 int total = roomPrice * orderObj.GetAmount() + tax + shippingHandlingCharges;
                 Console.ForegroundColor = ConsoleColor.Yellow;
                 Console.WriteLine("Order Processing...Please Wait");
                 Console.WriteLine("------------------------------");
                 Console.WriteLine("{0} placed a order for {1} rooms. Total Price = ${2}\n , {3} ", orderObj.GetSenderId(), orderObj.GetAmount(), total,roomPrice);
                 Console.ResetColor();
                 TravelAgency.orderConfirmation(orderObj);    //Calling the callback method of the retailer and sending order class object with it which contains the details of the processed order
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Oops! Error occurred in process order method " + e.Message);
     }
 }
 // Function to check buffer repeatedly for entries
 public void hotelFunction()
 {
     do
     {
         Monitor.Enter(MainSystem.mcb);
         try
         {
             for (int i = 0; i < 2; i++)                 // Check all 2 entries
             {
                 string encodedString = MainSystem.mcb.getOneCell(i, hotelID);
                 string[] stringTokens = null;
                 if(encodedString != null)
                     stringTokens = encodedString.Split('?');
                 if (stringTokens != null && stringTokens[0] != null)                        // If entry found
                 {
                     orderObject = EncoderDecoder.getDecodedValue(stringTokens[0]);
                     orderObject.setCreditCardNumber((client.Encrypt(orderObject.getCreditCardNumber().ToString())));
                     var t = new Thread(() => orderProcessing(orderObject, orderObject.getRoomPrice(), stringTokens[1]));      // Start processing order
                     Console.WriteLine("\n======================================================================");
                     Console.WriteLine("Order Received for the Hotel :"+  orderObject.getReceiverID());
                     Console.WriteLine("TravelAgency:{0}, RoomPrice:{1}, NumberOfRooms:{2}", orderObject.getSenderID(), orderObject.getRoomPrice(), orderObject.getNumberOfRooms());
                     Console.WriteLine("======================================================================");
                     t.Start();
                     t.Join();
                 }
             }
         }
         finally
         {
             Monitor.Exit(MainSystem.mcb);
         }
         Thread.Sleep(1000);
     } while (iterations != 100);
 }
 /// <summary>
 /// Constructor for the OrderProcesing
 /// </summary>
 /// <param name="order">Order to be processed</param>
 /// <param name="unitPrice">Unit Price for the Hotel Rooms</param>
 public OrderProcessing(OrderClass order, double unitPrice)
 {
     this.Order     = order;
     this.UnitPrice = unitPrice;
 }
 public void receiveConfirmation(OrderClass obj)
 {
     Console.WriteLine("Printing Confirmation at Travel Agency : " + obj.ToString());
     Console.WriteLine("Time of Order Confirmation = " + DateTime.Now + "\n------------");
 }
Esempio n. 22
0
        public static OrderClass decoder(String encodedString)
        {
            if (encodedString != null)
            {
                HotelBookingSystem.CryptService.ServiceClient decrypt = new HotelBookingSystem.CryptService.ServiceClient();
                String decodedString = decrypt.Decrypt(encodedString);
                int    index         = 0;
                String str           = "";
                while (decodedString[index] != '&')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                Int32 orderId = Convert.ToInt32(str);
                str.Remove(0);
                str = "";
                index++;

                while (decodedString[index] != '#')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                Int32 senderId = Convert.ToInt32(str);
                str.Remove(0);
                str = "";
                index++;

                while (decodedString[index] != '$')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                Int32 cardNo = Convert.ToInt32(str);
                str.Remove(0);
                str = "";
                index++;

                while (decodedString[index] != '?')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                Double unitPrice = Convert.ToDouble(str);
                str.Remove(0);
                str = "";
                index++;

                while (decodedString[index] != '%')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                Int32 amountOfRoom = Convert.ToInt32(str);
                str.Remove(0);
                str = "";
                index++;

                while (decodedString[index] != '@')
                {
                    str += decodedString[index].ToString();
                    index++;
                }
                DateTime senderTime = Convert.ToDateTime(str);
                //              Console.WriteLine("OrderId: {0} SenderId: {1} CardNo: {2} Amount: {3} Date: {4}", orderId, senderId, cardNo, amountOfRoom, senderTime);
                OrderClass order = new OrderClass();
                order.setOrderId(orderId);
                order.setSenderId(senderId);
                order.setCardNo(cardNo);
                order.setUnitPrice(unitPrice);
                order.setAmt(amountOfRoom);
                order.setSenderTime(senderTime);
                return(order);
            }
            else
            {
                Console.WriteLine("Null string!");
                return(null);
            }
        }