public void FundsTransferError(Guid pOrderGuid)
        {
            using (TransactionScope lScope = new TransactionScope())
            {
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        Console.WriteLine("Funds Transfer Error");
                        var pOrder = lContainer.Orders
                                     .Include("Customer").FirstOrDefault(x => x.OrderNumber == pOrderGuid);

                        EmailProvider.SendMessage(new EmailMessage()
                        {
                            ToAddress = pOrder.Customer.Email,
                            Message   = "You have insufficient funds in your bank account. Your order " + pOrderGuid + " has been cancelled."
                        });
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        Console.WriteLine("Error in FundsTransferError: " + lException.Message);
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public void addLike(int media_id, int userid)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             var h = from history in lContainer.PurchasedHistories
                     where history.Media.Id == media_id && history.User.Id == userid
                     select history;
             var m   = lContainer.Media.Include("Stocks").First(p => p.Id == media_id);
             var val = h.First();
             if (val.Rating == false)
             {
                 m.Like    += 1;
                 val.Rating = true;
             }
             else
             {
                 if (val.RateValue == 0)
                 {
                     m.Like    += 1;
                     m.Dislike -= 1;
                 }
             }
             val.RateValue = 1;
             val.RateDate  = DateTime.Now;
             lContainer.SaveChanges();
             lScope.Complete();
         }
 }
        public void DeliverySubmitted(Guid pOrderGuid, Guid pDeliveryGuid)
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                Console.WriteLine("Delivery for order: " + pOrderGuid + "has been submitted for delivery. Delivery id: " + pDeliveryGuid);
                var pOrder = lContainer.Orders.Include("Customer").First(x => x.OrderNumber == pOrderGuid);

                Delivery lDelivery = new Delivery()
                {
                    DeliveryStatus     = DeliveryStatus.Submitted,
                    SourceAddress      = "Book Store Address",
                    DestinationAddress = pOrder.Customer.Address,
                    Order = pOrder,
                    ExternalDeliveryIdentifier = pDeliveryGuid
                };
                pOrder.Delivery = lDelivery;
                lContainer.Deliveries.Add(lDelivery);

                //update stocks
                foreach (OrderItem lOrderItem in pOrder.OrderItems)
                {
                    int    book_id = lContainer.WBooks.Where(books => books.Title == lOrderItem.Book.Title).First().Id;
                    WStock lWStock = lContainer.WStocks.Where(stock => stock.Warehouse_id == pOrder.Warehouse_Id).Where(Stock => Stock.WBook_id == book_id).First();
                    lWStock.quantity -= lOrderItem.Quantity;
                }

                lContainer.SaveChanges();
                SendOrderPlacedConfirmation(pOrder);
            }
        }
Ejemplo n.º 4
0
        public List <Media> getRecommendationList(int media_id, int user_id)
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                var usersWithTheSameRate = from history in lContainer.PurchasedHistories
                                           where history.Media.Id == media_id && history.User.Id != user_id && history.RateValue == 1
                                           select history.User.Id;


                List <Media> result = new List <Media>();
                foreach (int userid in usersWithTheSameRate.ToList())
                {
                    var h = from history in lContainer.PurchasedHistories
                            where history.Media.Id != media_id && history.User.Id == userid && history.RateValue == 1
                            orderby history.RateDate descending
                            select history.Media.Id;
                    foreach (int t in h.ToList())
                    {
                        var m = lContainer.Media.Include("Stocks").First(p => p.Id == t);
                        result.Add(m);
                    }
                }


                lContainer.SaveChanges();
                return(result);
            }
        }
        public void SubmitOrder(Order pOrder)
        {
            using (TransactionScope lScope = new TransactionScope())
            {
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        LoadWarehouseStocks(pOrder);
                        FindWarehouse(pOrder);
                        pOrder.Warehouse   = lContainer.Warehouses.Where(warehouse => warehouse.Id == pOrder.Warehouse_Id).First().Name;
                        pOrder.Store       = "OnLine";
                        pOrder.OrderNumber = Guid.NewGuid();
                        foreach (OrderItem orderItem in pOrder.OrderItems)
                        {
                            lContainer.OrderItems.Add(orderItem);
                        }
                        lContainer.Orders.Add(pOrder);
                        Console.WriteLine("Order Received: " + pOrder.OrderNumber);
                        TransferFundsFromCustomer(UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber, (double)pOrder.Total, pOrder.OrderNumber, pOrder.Customer.Id);
                        Console.WriteLine("Funds Transfer Requested by Customer:" + pOrder.Customer.Id);

                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        SendOrderErrorMessage(pOrder, lException);
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void CancelOrder(int UserOrderID)
        {
            using (TransactionScope lScope = new TransactionScope())
            {
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    Order UserOrder = lContainer.Orders.Find(UserOrderID);

                    //re-add the stock quantities from the order back to the stock
                    UserOrder.ResetStockLevels();

                    //make use of the message queues here
                    try
                    {
                        //give the customer their money back
                        TransferFundsToCustomer(UserProvider.ReadUserById(UserOrder.Customer.Id).BankAccountNumber, UserOrder.Total ?? 0.0, (UserOrder.Id).ToString(), UserOrder.Customer.Email);
                    }
                    catch (EndpointNotFoundException)
                    {
                        Debug.WriteLine("Bank process not found please switch on for a full refund.");
                    }
                    //soft delete order from order table
                    UserOrder.Deleted = true;

                    //save changes
                    lContainer.SaveChanges();
                    lScope.Complete();
                }
            }
        }
Ejemplo n.º 7
0
        /*
         * Adds a new book Purchase into the db
         */
        public void AddPurchase(Media pMedia, User pUser)
        {
            // Ensure duplicate rows do not exist for the same media purchase
            if (CheckIfPurchaseExistsForMedia(pMedia.Id, pUser.Id))
            {
                return;
            }


            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    Purchase Purchase = new Purchase
                    {
                        Media = pMedia,
                        User  = pUser
                    };

                    lContainer.Users.Attach(pUser);
                    lContainer.Media.Attach(pMedia);
                    lContainer.Purchases.Add(Purchase);

                    lContainer.SaveChanges();
                    lScope.Complete();
                }
        }
Ejemplo n.º 8
0
 public void DeleteUser(User pUser)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             lContainer.Users.Remove(pUser);
             lContainer.SaveChanges();
         }
 }
Ejemplo n.º 9
0
 public void UpdateUser(User pUser)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             lContainer.Users.Add(pUser);
             lContainer.SaveChanges();
             lScope.Complete();
         }
 }
Ejemplo n.º 10
0
 public void UpdateUser(User pUser)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             lContainer.Entry(pUser).State = EntityState.Modified;
             lContainer.SaveChanges();
             lScope.Complete();
         }
 }
Ejemplo n.º 11
0
        public void SubmitOrder(int UserOrderID)

        //automatic one
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                Order pOrder = lContainer.Orders.Find(UserOrderID);
                using (TransactionScope lScope = new TransactionScope())
                {
                    //LoadBookStocks(pOrder);
                    //MarkAppropriateUnchangedAssociations(pOrder);
                    try
                    {
                        //get the warehouses again for logging when doing the delivery
                        int[][] confirmedOrders = ConfirmOrderWarehouseLogicSave(pOrder);

                        // ask the delivery service to organise delivery
                        try
                        {
                            PlaceDeliveryForOrder(pOrder, confirmedOrders);
                        }
                        catch (EndpointNotFoundException)
                        {
                            Debug.WriteLine("DeliveryCo process is offline. Please switch back on for your delivery to be submitted.");
                            return;
                        }

                        // and save the order
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        try
                        {
                            SendOrderErrorMessage(pOrder, lException);
                        }
                        catch
                        {
                            Debug.WriteLine("An error has occurred but your email process is switched off. Please switch back on the email process to find out more.");
                        }
                    }
                }
                try
                {
                    SendOrderPlacedConfirmation(pOrder);
                }
                catch
                {
                    Debug.WriteLine("Email process is off. Switch on please in order to maintain communication with BookStore");
                }
            }
        }
 private void UpdateDeliveryStatus(Guid pDeliveryId, DeliveryStatus status)
 {
     using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
     {
         Delivery lDelivery = lContainer.Deliveries.Where((pDel) => pDel.ExternalDeliveryIdentifier == pDeliveryId).First();
         if (lDelivery != null)
         {
             lDelivery.DeliveryStatus = status;
             lContainer.SaveChanges();
         }
     }
 }
Ejemplo n.º 13
0
        public void SubmitOrder(Entities.Order pOrder)
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    AttachEntitiesToContext(lContainer, pOrder);

                    pOrder.UpdateStockLevels();

                    lContainer.SaveChanges();
                    lScope.Complete();
                }
        }
 private void UpdateDeliveryStatus(Guid pDeliveryId, DeliveryStatus status)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             Delivery lDelivery = lContainer.Deliveries.Where((pDel) => pDel.ExternalDeliveryIdentifier == pDeliveryId).FirstOrDefault();
             if (lDelivery != null)
             {
                 lDelivery.DeliveryStatus = status;
                 lContainer.SaveChanges();
             }
             lScope.Complete();
         }
 }
Ejemplo n.º 15
0
 public void createHistory(User user, Media media)
 {
     using (TransactionScope lScope = new TransactionScope())
         using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
         {
             lContainer.Users.Attach(user);
             lContainer.Media.Attach(media);
             media.Stocks = lContainer.Media.Include("Stocks").First(p => p.Id == media.Id).Stocks;
             lContainer.PurchasedHistories.Add(new PurchasedHistory {
                 User = user, Media = media, Rating = false, RateDate = DateTime.Now
             });
             lContainer.SaveChanges();
             lScope.Complete();
         }
 }
Ejemplo n.º 16
0
        private static void InsertCatalogueEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
            {
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    if (lContainer.Books.Count() == 0)
                    {
                        Book lGreatExpectations = new Book()
                        {
                            Author = "Jane Austen",
                            Genre  = "Fiction",
                            Price  = 20.0,
                            Title  = "Pride and Prejudice"
                        };

                        lContainer.Books.Add(lGreatExpectations);

                        Book lSoloist = new Book()
                        {
                            Author = "Charles Dickens",
                            Genre  = "Fiction",
                            Price  = 15.0,
                            Title  = "Grape Expectations"
                        };

                        lContainer.Books.Add(lSoloist);

                        for (int i = 1; i < 10; i++)
                        {
                            Book lItem = new Book()
                            {
                                Author = String.Format("Author {0}", i.ToString()),
                                Genre  = String.Format("Genre {0}", i),
                                Price  = i,
                                Title  = String.Format("Title {0}", i)
                            };
                            lContainer.Books.Add(lItem);
                        }

                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                }
            }
        }
        public void FundsTransferSuccessful(Guid pOrderGuid)
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                try
                {
                    Console.WriteLine("Funds Transfer Successful.");
                    Order pOrder = lContainer.Orders.Include("OrderItems").First(x => x.OrderNumber == pOrderGuid);
                    PlaceDeliveryForOrder(pOrder);

                    lContainer.SaveChanges();
                }
                catch (Exception lException)
                {
                    Console.WriteLine("Error in Placing Delivery Order: " + lException.Message);
                    throw;
                }
            }
        }
Ejemplo n.º 18
0
        /*
         * Rates or re-rates a book if purchased
         */
        public void RateMedia(bool pLike, User pUser, Media pMedia)
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    // Check if the user has actually purchased the book before rating it
                    if (!CheckIfPurchaseExistsForMedia(pMedia.Id, pUser.Id))
                    {
                        return;
                    }

                    var Rating = lContainer.Ratings.Include("User").Include("Media").SingleOrDefault(r => r.Media.Id == pMedia.Id && r.User.Id == pUser.Id);

                    if (Rating != null)
                    {
                        if (pLike == true)
                        {
                            LikeMedia(Rating);
                        }
                        else
                        {
                            DislikeMedia(Rating);
                        }
                    }
                    else
                    {
                        Rating NewRating = new Rating
                        {
                            Like  = pLike,
                            User  = pUser,
                            Media = pMedia
                        };

                        lContainer.Users.Attach(pUser);
                        lContainer.Media.Attach(pMedia);
                        lContainer.Ratings.Add(NewRating);
                    }

                    lContainer.SaveChanges();
                    lScope.Complete();
                }
        }
        public void LoadWarehouseStocks(Order pOrder)
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                foreach (OrderItem lOrderItem in pOrder.OrderItems)
                {
                    String Btitle = lOrderItem.Book.Title;

                    int BookId = lContainer.WBooks.Where(wbook => Btitle == wbook.Title).First().Id;
                    foreach (WStock IWstock in lContainer.WStocks.ToList())
                    {
                        if (IWstock.WBook_id == BookId)
                        {
                            lOrderItem.Book.WStocks.Add(IWstock);
                        }
                    }
                }
                lContainer.SaveChanges();
            }
        }
Ejemplo n.º 20
0
        private static void InsertCatalogueEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    if (lContainer.Media.Count() == 0)
                    {
                        Media lGreatExpectations = new Media()
                        {
                            Author = "Rene Clair",
                            Genre  = "Fiction",
                            Price  = 20.0M,
                            Title  = "And Then there were None"
                        };

                        lContainer.Media.Add(lGreatExpectations);


                        Stock lGreatExpectationsStock = new Stock()
                        {
                            Media     = lGreatExpectations,
                            Quantity  = 5,
                            Warehouse = "Neutral Bay"
                        };

                        lContainer.Stocks.Add(lGreatExpectationsStock);

                        Media lSoloist = new Media()
                        {
                            Author = "The Soloist",
                            Genre  = "Fiction",
                            Price  = 15.0M,
                            Title  = "The Soloist"
                        };

                        lContainer.Media.Add(lSoloist);

                        Stock lSoloistStock = new Stock()
                        {
                            Media     = lSoloist,
                            Quantity  = 7,
                            Warehouse = "Neutral Bay"
                        };

                        lContainer.Stocks.Add(lSoloistStock);

                        for (int i = 0; i < 30; i++)
                        {
                            Media lItem = new Media()
                            {
                                Author = String.Format("Director {0}", i.ToString()),
                                Genre  = String.Format("Genre {0}", i),
                                Price  = i,
                                Title  = String.Format("Title {0}", i)
                            };

                            lContainer.Media.Add(lItem);

                            Stock lStock = new Stock()
                            {
                                Media     = lItem,
                                Quantity  = 7,
                                Warehouse = String.Format("Warehouse {0}", i)
                            };

                            lContainer.Stocks.Add(lStock);
                        }


                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                }
        }
Ejemplo n.º 21
0
        public Order ConfirmOrder(Entities.Order pOrder)

        //checks if the order is possible
        {
            using (TransactionScope lScope = new TransactionScope())
            {
                //LoadBookStocks(pOrder);
                //MarkAppropriateUnchangedAssociations(pOrder);

                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        pOrder.OrderNumber   = Guid.NewGuid();
                        pOrder.Store         = "OnLine";
                        pOrder.ProcessStatus = 0;

                        // Book objects in pOrder are missing the link to their Stock tuple (and the Stock GUID field)
                        // so fix up the 'books' in the order with well-formed 'books' with 1:1 links to Stock tuples
                        foreach (OrderItem lOrderItem in pOrder.OrderItems)
                        {
                            int bookId = lOrderItem.Book.Id;
                            lOrderItem.Book = lContainer.Books.Where(book => bookId == book.Id).First();
                            System.Guid stockId = lOrderItem.Book.Stock.Id;
                            lOrderItem.Book.Stock = lContainer.Stocks.Where(stock => stockId == stock.Id).First();
                        }

                        // confirm the order can be completed and from which warehouses
                        int[][] confirmedOrders = ConfirmOrderWarehouseLogic(pOrder);
                        Debug.WriteLine(pOrder.ProcessStatus);
                        // an error has occured when confirming the order
                        if (confirmedOrders[0][0] == -1)
                        {
                            SendOrderFailedConfirmation(pOrder);
                            pOrder.ProcessStatus = 1;
                            Debug.WriteLine(pOrder.ProcessStatus);
                            return(pOrder);
                        }
                        Debug.WriteLine(pOrder.ProcessStatus);
                        // and update the stock levels
                        try
                        {
                            pOrder.UpdateStockLevels();
                        }
                        catch (Exception)
                        {
                            pOrder.ProcessStatus = 1;
                            return(pOrder);
                        }

                        // add the modified Order tree to the Container (in Changed state)
                        lContainer.Orders.Add(pOrder);

                        // ask the Bank service to transfer fundss
                        lContainer.SaveChanges();

                        //TransferFundsFromCustomer(UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber, pOrder.Total ?? 0.0, pOrder.OrderNumber.ToString());
                        try
                        {
                            TransferFundsFromCustomer(UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber, pOrder.Total ?? 0.0, pOrder.Id.ToString(), pOrder.Customer.Email);
                        }
                        catch (EndpointNotFoundException)
                        {
                            pOrder.ProcessStatus = 2;
                            return(pOrder);
                        }

                        // and save the order
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        try
                        {
                            SendOrderErrorMessage(pOrder, lException);
                        }
                        catch
                        {
                            Debug.WriteLine("Email process is off. Switch on please in order to maintain communication with BookStore");
                        }
                    }
                }
            }
            return(pOrder);
        }
Ejemplo n.º 22
0
        public void CancelOrder(int pOrderId)
        {
            String customerEmail = "";
            Guid   orderNumber   = Guid.Empty;

            using (TransactionScope lScope = new TransactionScope())
            {
                //LoadBookStocks(pOrder);
                //MarkAppropriateUnchangedAssociations(pOrder);

                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    Order  lOrder = lContainer.Orders.FirstOrDefault(o => o.Id == pOrderId);
                    string result = "";
                    try
                    {
                        if (lOrder == null)
                        {
                            throw new OrderDoesNotExistException();
                        }
                        if (lOrder.Delivery != null)
                        {
                            throw new OrderHasAlreadyBeenDeliveredException();
                        }

                        customerEmail = lOrder.Customer.Email;
                        orderNumber   = lOrder.OrderNumber;

                        List <OrderItem> orderItems = lOrder.OrderItems.ToList <OrderItem>();

                        Console.WriteLine("================Cancel Order=================");
                        Console.WriteLine("             Order ID: " + pOrderId);
                        Console.WriteLine("             CustomerID: " + lOrder.Customer.Id);
                        Console.WriteLine("             Name: " + lOrder.Customer.Name);
                        Console.WriteLine("             Address: " + lOrder.Customer.Address);
                        Console.WriteLine("             Time: " + DateTime.Now);
                        Console.WriteLine("Items Restored: ");

                        foreach (OrderItem lOrderItem in orderItems)
                        {
                            Console.WriteLine("             " + lOrderItem.Book.Title + ": Quantity " + lOrderItem.Quantity);
                        }

                        Console.WriteLine("=============================================" + "\n");
                        Console.WriteLine(" ");

                        // Restore stocks
                        RestoreStock(orderItems, lContainer);

                        // ask the Bank service to transfer fundss
                        result = TransferFundsToCustomer(UserProvider.ReadUserById(lOrder.Customer.Id).BankAccountNumber, lOrder.Total ?? 0.0);

                        // Delete the delivery in the delivery table
                        DeleteDelivery(lOrder.OrderNumber.ToString());

                        lOrder.OrderItems.ToList().ForEach(o => { lContainer.Entry(o).State = System.Data.Entity.EntityState.Deleted; });
                        lContainer.Entry(lOrder).State = System.Data.Entity.EntityState.Deleted;
                        lContainer.Orders.Remove(lOrder);

                        // save the changes
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        Console.WriteLine("================Cancel Order=================");
                        Console.WriteLine("             Order ID: " + pOrderId);
                        Console.WriteLine("             CustomerID: " + lOrder.Customer.Id);
                        Console.WriteLine("             Name: " + lOrder.Customer.Name);
                        Console.WriteLine("             Address: " + lOrder.Customer.Address);
                        Console.WriteLine("             Time: " + DateTime.Now);
                        Console.WriteLine("Failed to restore the order items");

                        Console.WriteLine("=============================================" + "\n");
                        Console.WriteLine(" ");

                        // need to rollback bank transfer if the transfer happened
                        if (result == "Transfer Success")
                        {
                            TransferFundsFromCustomer(UserProvider.ReadUserById(lOrder.Customer.Id).BankAccountNumber, lOrder.Total ?? 0.0);
                        }
                        SendOrderErrorMessage(lOrder, lException);
                        IEnumerable <System.Data.Entity.Infrastructure.DbEntityEntry> entries = lContainer.ChangeTracker.Entries();
                    }
                }
            }
            // we have a customer to send the cancelled confirmation to
            if (customerEmail != "" && orderNumber != Guid.Empty)
            {
                SendOrderCancelledConfirmation(customerEmail, orderNumber);
            }
        }
Ejemplo n.º 23
0
        public string SubmitOrder(Entities.Order pOrder)
        {
            string lCustomerEmail = "";
            Guid   lOrderId       = Guid.Empty;

            using (TransactionScope lScope = new TransactionScope())
            {
                //LoadBookStocks(pOrder);
                //MarkAppropriateUnchangedAssociations(pOrder);
                string lResult = "";

                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        lContainer.Users.Attach(pOrder.Customer);

                        pOrder.OrderNumber = Guid.NewGuid();
                        pOrder.Store       = "OnLine";
                        lCustomerEmail     = pOrder.Customer.Email;
                        lOrderId           = pOrder.OrderNumber;

                        // Book objects in pOrder are missing the link to their Stock tuple (and the Stock GUID field)
                        // so fix up the 'books' in the order with well-formed 'books' with 1:1 links to Stock tuples
                        foreach (OrderItem lOrderItem in pOrder.OrderItems)
                        {
                            int bookId = lOrderItem.Book.Id;
                            lOrderItem.Book        = lContainer.Books.Where(book => bookId == book.Id).First();
                            lOrderItem.Book.Stocks = lContainer.Stocks.Where(stock => bookId == stock.Book.Id).ToList <Stock>();
                        }

                        List <Warehouse> bestWares = LoadOptimalWarehouseStocks(pOrder);

                        // cannot satisfy
                        if (bestWares.Count == 0)
                        {
                            throw new Exception("Insufficient stock");
                        }

                        // and update the stock levels
                        List <Tuple <Stock, OrderItem, int> > lConsumedStocks = pOrder.UpdateStockLevels(bestWares, lContainer);

                        // record the stocks that have been consumed
                        RecordPurchasedBooksFromStocks(lConsumedStocks, lContainer);

                        // add the modified Order tree to the Container (in Changed state)
                        lContainer.Orders.Add(pOrder);

                        // ask the Bank service to transfer fundss
                        lResult = TransferFundsFromCustomer(UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber, pOrder.Total ?? 0.0);

                        if (!lResult.Equals("Transfer Success"))
                        {
                            // Email the user about the cause of error through this exception
                            throw new Exception(lResult);
                        }

                        Console.WriteLine("=============Order Submit=============");
                        Console.WriteLine("Order ID: " + pOrder.Id);
                        Console.WriteLine("Status: SUCCESS");
                        Console.WriteLine("Time: " + DateTime.Now);
                        Console.WriteLine("======================================");
                        Console.WriteLine(" ");

                        // and save the order
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        Console.WriteLine("=============Order Submit=============");
                        Console.WriteLine("Order ID: " + pOrder.Id);
                        Console.WriteLine("Status: FAILED");
                        Console.WriteLine("Time: " + DateTime.Now);
                        Console.WriteLine("======================================");
                        Console.WriteLine(" ");

                        // need to rollback bank transfer if the transfer happened
                        if (lResult == "Transfer Success")
                        {
                            Console.WriteLine("=============Calling BANK - Rollback=============");
                            Console.WriteLine("Intiating ROLLBACK on bank trasnfer");
                            Console.WriteLine("Order ID: " + pOrder.Id);
                            Console.WriteLine("Acc Number: " + UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber);
                            Console.WriteLine("Total: " + pOrder.Total);
                            Console.WriteLine("Time: " + DateTime.Now);
                            Console.WriteLine("======================================");
                            Console.WriteLine(" ");
                            TransferFundsToCustomer(UserProvider.ReadUserById(pOrder.Customer.Id).BankAccountNumber, pOrder.Total ?? 0.0);
                        }
                        SendOrderErrorMessage(pOrder, lException);
                        IEnumerable <System.Data.Entity.Infrastructure.DbEntityEntry> entries = lContainer.ChangeTracker.Entries();
                        return(lResult);
                    }
                }
            }

            SendOrderConfirmedConfirmation(pOrder);

            // User has 20 seconds to cancel the order
            Thread.Sleep(20000);

            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        Order lOrder = lContainer.Orders.Where(o => o.Id == pOrder.Id).FirstOrDefault <Order>();
                        if (lOrder == null)
                        {
                            throw new Exception("Cannot place order as your order was cancelled");
                        }
                        CreateDelivery(lOrder);
                        lContainer.SaveChanges();
                        lScope.Complete();
                    } catch (Exception lException)
                    {
                        SendOrderDeletedErrorMessage(lCustomerEmail, lOrderId);
                        return("Order Failed");
                    }
                }

            // 5 seconds later the order will be scheduled for delivery
            Thread.Sleep(5000);

            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    try
                    {
                        Order lOrder = lContainer.Orders.Where(o => o.Id == pOrder.Id).FirstOrDefault <Order>();
                        if (lOrder == null)
                        {
                            throw new Exception("Cannot place order as your order was cancelled");
                        }
                        Delivery lDelivery = lContainer.Deliveries.Where(d => d.Order.Id == lOrder.Id).FirstOrDefault <Delivery>();
                        PlaceDeliveryForOrder(lOrder, lDelivery);
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                    catch (Exception lException)
                    {
                        SendOrderDeletedErrorMessage(lCustomerEmail, lOrderId);
                        return("Order Failed");
                    }
                }

            SendOrderPlacedConfirmation(pOrder);
            return("Order Submitted");
        }
Ejemplo n.º 24
0
        private static void InsertCatalogueEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    if (lContainer.Books.Count() == 0)
                    {
                        Book lGreatExpectations = new Book()
                        {
                            Author = "Jane Austen",
                            Genre  = "Fiction",
                            Price  = 20.0,
                            Title  = "Pride and Prejudice"
                        };

                        lContainer.Books.Add(lGreatExpectations);

                        Stock lGreatExpectationsStock = new Stock()
                        {
                            Book       = lGreatExpectations,
                            Quantity   = 5,
                            Warehouses = new List <Warehouse>()
                        };
                        Warehouse A = new Warehouse()
                        {
                            Quantity = 5
                        };
                        lGreatExpectationsStock.Warehouses.Add(A);
                        lContainer.Stocks.Add(lGreatExpectationsStock);
                        lContainer.Warehouses.Add(A);

                        //System.Diagnostics.Debug.WriteLine(lGreatExpectationsStock.Id);
                        //System.Diagnostics.Debug.WriteLine("Id 1");

                        Book lSoloist = new Book()
                        {
                            Author = "Charles Dickens",
                            Genre  = "Fiction",
                            Price  = 15.0,
                            Title  = "Grape Expectations"
                        };

                        lContainer.Books.Add(lSoloist);

                        Stock lSoloistStock = new Stock()
                        {
                            Book       = lSoloist,
                            Quantity   = 7,
                            Warehouses = new List <Warehouse>()
                        };
                        Warehouse B = new Warehouse()
                        {
                            Quantity = 7
                        };
                        lSoloistStock.Warehouses.Add(B);
                        lContainer.Stocks.Add(lSoloistStock);
                        lContainer.Warehouses.Add(B);

                        //System.Diagnostics.Debug.WriteLine(lSoloistStock.Id);
                        //System.Diagnostics.Debug.WriteLine("Id 2");


                        for (int i = 1; i < 10; i++)
                        {
                            Book lItem = new Book()
                            {
                                Author = String.Format("Author {0}", i.ToString()),
                                Genre  = String.Format("Genre {0}", i),
                                Price  = i,
                                Title  = String.Format("Title {0}", i)
                            };

                            Stock lStock = new Stock()
                            {
                                Book       = lItem,
                                Quantity   = 10 + i,
                                Warehouses = new List <Warehouse>()
                            };
                            Warehouse C = new Warehouse()
                            {
                                Quantity = 10 + i
                            };
                            lStock.Warehouses.Add(C);
                            lContainer.Stocks.Add(lStock);
                            lContainer.Warehouses.Add(C);
                        }
                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                }
        }
        public int[][] ProcessOrderSave(Order pOrder)
        {
            using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
            {
                // make return matrix to maximum required height
                int max_entries = 0;
                foreach (OrderItem order in pOrder.OrderItems)
                {
                    max_entries += order.Quantity;
                }

                int[][] result = new int[max_entries][];

                for (int i = 0; i < max_entries; i++)
                {
                    result[i] = new int[] { 0, 0, 0 };
                }

                int index         = 0;
                int orderQuantity = 0;

                // for each individual order
                foreach (OrderItem order in pOrder.OrderItems)
                {
                    orderQuantity = order.Quantity;

                    // get the book for the order
                    Book book = order.Book;

                    // look at each of the warehouses that contain the book
                    foreach (Warehouse wh in book.Stock.Warehouses)
                    {
                        // fill the results matrix
                        result[index][0] = book.Id;
                        result[index][1] = wh.Id;
                        result[index][2] = (int)wh.Quantity >= orderQuantity ? orderQuantity : (int)wh.Quantity;

                        // if the warehouse has enough quanity in stock
                        if (wh.Quantity >= orderQuantity)
                        {
                            // reduce the quantity of the warehouse
                            wh.Quantity -= orderQuantity;

                            // empty the order
                            orderQuantity = 0;

                            // break the loop because the order has been completed
                            break;
                        }
                        // if the warehouse does not have enough in stock
                        else
                        {
                            // reduce the quantity of the order
                            orderQuantity -= (int )wh.Quantity;

                            // empty the warehouse of it's stock for this book
                            wh.Quantity = 0;
                        }

                        index++;
                    }

                    // if the if there is quantity left over then the order can't go through
                    if (orderQuantity > 0)
                    {
                        // setup the error matrix
                        result[0][0] = -1;

                        // return the error matrix
                        return(result);
                    }
                }

                lContainer.SaveChanges();

                // return the processed orders
                return(result);
            }
        }
Ejemplo n.º 26
0
        private static void InsertCatalogueEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    if (lContainer.Books.Count() == 0)
                    {
                        Warehouse lNeutralBay = new Warehouse()
                        {
                            Name    = "Neutral Bay",
                            Address = "1 Neutral Bay"
                        };

                        Warehouse lTheWarehouse = new Warehouse()
                        {
                            Name    = "The Warehouse",
                            Address = "1 The Warehouse"
                        };

                        Warehouse lStorageKing = new Warehouse()
                        {
                            Name    = "Storage King",
                            Address = "1 Storage King"
                        };

                        Warehouse lAmazon = new Warehouse()
                        {
                            Name    = "Amazon",
                            Address = "1 Amazon St"
                        };

                        Book lGreatExpectations = new Book()
                        {
                            Author = "Anonymous",
                            Genre  = "Fiction",
                            Price  = 10.0,
                            Title  = "The Great Expectations",
                        };

                        Book lSoloist = new Book()
                        {
                            Author = "Charles Dickens",
                            Genre  = "Fiction",
                            Price  = 15.0,
                            Title  = "The Solo"
                        };

                        Book lMuhitAnik = new Book()
                        {
                            Author = "Muhit Anik",
                            Genre  = "Philosophy",
                            Price  = 20.0,
                            Title  = "The Journey of Muhit Anik",
                        };


                        Stock lGreatExpectationNeutralBayStock   = CreateStock(lGreatExpectations, lNeutralBay, 10);
                        Stock lGreatExpectationTheWarehouseStock = CreateStock(lGreatExpectations, lTheWarehouse, 0);
                        Stock lGreatExpectationStorageKingStock  = CreateStock(lGreatExpectations, lStorageKing, 0);
                        Stock lGreatExpectationAmazonStock       = CreateStock(lGreatExpectations, lAmazon, 10);

                        Stock lSoloistNeutralBayStock   = CreateStock(lSoloist, lNeutralBay, 0);
                        Stock lSoloistTheWarehouseStock = CreateStock(lSoloist, lTheWarehouse, 10);
                        Stock lSoloistStorageKingStock  = CreateStock(lSoloist, lStorageKing, 0);
                        Stock lSoloistAmazonStock       = CreateStock(lSoloist, lAmazon, 10);


                        Stock lNoBookNeutralBayStock   = CreateStock(lMuhitAnik, lNeutralBay, 0);
                        Stock lNoBookTheWarehouseStock = CreateStock(lMuhitAnik, lTheWarehouse, 0);
                        Stock lNoBookStorageKingStock  = CreateStock(lMuhitAnik, lStorageKing, 10);
                        Stock lNoBookAmazonStock       = CreateStock(lMuhitAnik, lAmazon, 10);

                        lContainer.Books.Add(lGreatExpectations);
                        lContainer.Books.Add(lSoloist);
                        lContainer.Books.Add(lMuhitAnik);

                        lContainer.Stocks.Add(lGreatExpectationNeutralBayStock);
                        lContainer.Stocks.Add(lGreatExpectationTheWarehouseStock);
                        lContainer.Stocks.Add(lGreatExpectationStorageKingStock);
                        lContainer.Stocks.Add(lGreatExpectationAmazonStock);

                        lContainer.Stocks.Add(lSoloistNeutralBayStock);
                        lContainer.Stocks.Add(lSoloistStorageKingStock);
                        lContainer.Stocks.Add(lSoloistTheWarehouseStock);
                        lContainer.Stocks.Add(lSoloistAmazonStock);

                        lContainer.Stocks.Add(lNoBookNeutralBayStock);
                        lContainer.Stocks.Add(lNoBookTheWarehouseStock);
                        lContainer.Stocks.Add(lNoBookStorageKingStock);
                        lContainer.Stocks.Add(lNoBookAmazonStock);

                        for (int i = 5; i < 31; i++)
                        {
                            Book lItem = new Book()
                            {
                                Author = String.Format("Author {0}", i.ToString()),
                                Genre  = String.Format("Genre {0}", i),
                                Price  = i,
                                Title  = String.Format("Title {0}", i)
                            };

                            lContainer.Books.Add(lItem);

                            Warehouse lWarehouse = new Warehouse()
                            {
                                Name    = String.Format("The Warehouse {0}", i),
                                Address = String.Format("Warehouse {0}'s palace", i)
                            };

                            Stock lStock = new Stock()
                            {
                                Book     = lItem,
                                Quantity = 10 + i,
                                // Warehouse = String.Format("Warehouse {0}", i)
                                Warehouse = lWarehouse
                            };

                            lContainer.Warehouses.Add(lWarehouse);
                            lContainer.Stocks.Add(lStock);
                        }

                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                }
        }