public async Task<ActionResult> Create([Bind] OrderViewViewModel orderModel) { if (ModelState.IsValid) { // Unpack data from form and collect the necessary missing data Order order = new Order(); order.CustomerId = orderModel.CustomerID; order.CreatedDate = DateTime.Now; // Get the employee object attached to the logged in user var currentUser = User.Identity.GetUserId(); var employee = db.Employees.First(emp => emp.AspNetUserID == currentUser); order.SoldById = employee.EmployeeID; List<OrderProduct> orderProducts = new List<OrderProduct>(); foreach(int productID in orderModel.ProductID) { OrderProduct orderProduct = new OrderProduct(); orderProduct.OrderId = -1; orderProduct.ProductId = productID; orderProducts.Add(orderProduct); } // Create the PackagedOrder, which will be sent through the Service Bus to the API PackagedOrder newOrder = new PackagedOrder(); newOrder.Order = order; newOrder.OrderProducts = orderProducts; // Handle timezone information. Client will send it in their local time. DateTimeZoneHandling.RoundtripKind maintains the timezone information in the DateTime // so it can be easily converted to the client's local time later on. JsonSerializerSettings jsonSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind }; // Serialize the PackagedOrder to JSON to send in the Service Bus string jsonOrder = JsonConvert.SerializeObject(newOrder, jsonSettings); // Create the message to be sent from the PackagedOrder var message = new BrokeredMessage(jsonOrder); // Asynchronously send the message to the Service Bus await QueueConnector.Client.SendAsync(message); return RedirectToAction("Index"); } PopulateViewBag(orderModel.ProductID); return View(orderModel); }
/// <summary> /// Insert the Order and OrderProducts into the database. /// </summary> /// <param name="packagedOrder">PackagedOrder object received from the Service Bus.</param> private void InsertPackagedOrder(PackagedOrder packagedOrder) { try { // Create the database connection and context // Since it's in a using-block, it will automatically dispose of the connection when it exits the block using (CS401_DBEntities1 db = new CS401_DBEntities1()) { var order = packagedOrder.Order; // Add the order to the db context db.Orders.Add(order); // Insert order to get an OrderID db.SaveChanges(); foreach (var orderProduct in packagedOrder.OrderProducts) { orderProduct.OrderId = order.OrderId; db.OrderProducts.Add(orderProduct); } // Insert OrderProducts into database now db.SaveChanges(); } } catch (Exception ex) { Trace.WriteLine("Error inserting data into db: " + ex.Message); SendErrorMessage(ex); } }