Example #1
0
 public static void PrintPlan(DeliveryPlan plan)
 {
     Console.WriteLine($"Shortest path for Address: {plan.Customer.Address}");
     Console.WriteLine($"---------------------------------------------------------------");
     Console.WriteLine($"Depot:{plan.Depot.Address} -> Store: {plan.Store.Address} -> Customer: {plan.Customer.Address}");
     Console.WriteLine($"Total Delivery Time: {(int)plan.TotalDeliveryTime.TotalMinutes}:{plan.TotalDeliveryTime.Seconds}");
 }
Example #2
0
 public ActionResult AddOrEdit(DeliveryPlan deliveryPlan)
 {
     if (deliveryPlan.DeliveryPlanId == 0)
     {
         if (deliveryPlanService.Add(deliveryPlan))
         {
             return(Json(new { success = true, message = "Add successfully" }, JsonRequestBehavior.AllowGet));
         }
         else
         {
             return(Json(new { success = false, message = "Failed to add" }, JsonRequestBehavior.AllowGet));
         }
     }
     else
     {
         if (deliveryPlanService.Edit(deliveryPlan))
         {
             return(Json(new { success = true, message = "Edit successfully" }, JsonRequestBehavior.AllowGet));
         }
         else
         {
             return(Json(new { success = false, message = "Failed to edit" }, JsonRequestBehavior.AllowGet));
         }
     }
 }
Example #3
0
        public ActionResult Remove(int id)
        {
            DeliveryPlan deliveryPlan = deliveryPlanService.GetOne(id);

            deliveryPlanService.Delete(deliveryPlan);
            return(Json(new { success = true, message = "Removal success!" }, JsonRequestBehavior.AllowGet));
        }
Example #4
0
        public ActionResult DeleteConfirmed(int id)
        {
            DeliveryPlan deliveryPlan = deliveryPlanService.GetOne(id);

            deliveryPlanService.Delete(deliveryPlan);
            return(RedirectToAction("Index"));
        }
Example #5
0
        /// <summary>
        /// Calculates closest distance between customer, depot and drone.
        /// </summary>
        /// <param name="customerAddress">Address of a customer</param>
        /// <returns>DeliveryPlan, which contains routes and estimated time.</returns>
        public async Task <DeliveryPlan> Calculate(string customerAddress)
        {
            DeliveryPlan plan     = new DeliveryPlan();
            Location     customer = new Location();

            customer = await _locationService.Find(customerAddress);

            plan.Customer = customer;
            IList <ShortestPathResult>    pathResults = new List <ShortestPathResult>();
            Dictionary <uint, DroneDepot> DepotMap    = new Dictionary <uint, DroneDepot>();
            Dictionary <uint, Store>      StoreMap    = new Dictionary <uint, Store>();

            // Creating graph to be able to use Dijkstra algorithm to find the shortest path.
            var  graph      = new Graph <string, string>();
            uint customerId = graph.AddNode("Customer");

            foreach (DroneDepot depot in Depots)
            {
                uint depotId = graph.AddNode(depot.Name);
                DepotMap.Add(depotId, depot);
                foreach (Store store in _stores)
                {
                    uint storeId = graph.AddNode(store.Name);
                    StoreMap.Add(storeId, store);

                    // converting KM to M, because the cost variable is int, so the accuracy will be in meters.
                    graph.Connect(depotId, storeId, (int)(depot.Coordinate.Distance(store.Coordinate) * 1000), $"{depot.Name} -> {store.Name}");
                    graph.Connect(storeId, customerId, (int)(store.Coordinate.Distance(customer.Coordinate) * 1000), $"{store.Name} -> Customer");
                }
                pathResults.Add(graph.Dijkstra(depotId, customerId));
            }

            // Find the shortest path from path results. Depot -> Store -> Customer
            ShortestPathResult shortestPath = pathResults[0];

            for (int i = 1; i < pathResults.Count; i++)
            {
                shortestPath = pathResults[i].Distance < shortestPath.Distance ? pathResults[i] : shortestPath;
            }

            // Get chosen shortest distance units.
            IList <uint> nodeList = shortestPath.GetPath().ToList();

            plan.Depot = DepotMap.Where(x => x.Key == nodeList[0]).Select(x => x.Value).SingleOrDefault();
            plan.Store = StoreMap.Where(x => x.Key == nodeList[1]).Select(x => x.Value).SingleOrDefault();

            // Calculate delivery time.
            double hours = shortestPath.Distance / DRONESPEED;

            plan.TotalDeliveryTime = TimeSpan.FromSeconds(hours);

            return(plan);
        }
Example #6
0
        // POST: Products/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult Create([Bind(Include = "ProductId,ProductName,Price,Description,CategoryId")] DeliveryPlan deliveryPlan)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        deliveryPlanService.Add(deliveryPlan);
        //        return RedirectToAction("Index");
        //    }

        //    ViewBag.CategoryId = new SelectList(CategoriesForSelectList(), "CategoryId", "CategoryName", deliveryPlan.CategoryId);
        //    return View(deliveryPlan);
        //}

        // GET: Products/Edit/5
        //public ActionResult Edit(int id)
        //{
        //    if (id == 0)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    DeliveryPlan deliveryPlan = deliveryPlanService.GetOne(id);
        //    if (deliveryPlan == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    ViewBag.CategoryId = new SelectList(CategoriesForSelectList(), "CategoryId", "CategoryName", deliveryPlan.CategoryId);
        //    return View(deliveryPlan);
        //}

        // POST: Products/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult Edit([Bind(Include = "ProductId,ProductName,Price,Description,CategoryId")] DeliveryPlan deliveryPlan)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        deliveryPlanService.Edit(deliveryPlan);
        //        return RedirectToAction("Index");
        //    }
        //    ViewBag.CategoryId = new SelectList(CategoriesForSelectList(), "CategoryId", "CategoryName", deliveryPlan.CategoryId);
        //    return View(deliveryPlan);
        //}

        // GET: Products/Delete/5
        public ActionResult Delete(int id)
        {
            if (id == 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryPlan deliveryPlan = deliveryPlanService.GetOne(id);

            if (deliveryPlan == null)
            {
                return(HttpNotFound());
            }
            return(View(deliveryPlan));
        }
Example #7
0
        public async Task <DeliveryPlanResult> Get([Required] string address)
        {
            DeliveryPlan plan = await _distanceService.Calculate(address);

            return(new DeliveryPlanResult()
            {
                Customer = plan.Customer.Address,
                Depot = plan.Depot.Address,
                Store = plan.Store.Address,
                DeliveryTime = new DeliveryTime()
                {
                    Minutes = (int)plan.TotalDeliveryTime.TotalMinutes,
                    Seconds = plan.TotalDeliveryTime.Seconds
                }
            });
        }
Example #8
0
        public ActionResult AddOrEdit(int id = 0)
        {
            List <Order> orders = orderService.GetAll();

            ViewBag.OrderId = new SelectList(orders, "OrderID", "OrderId");

            if (id == 0)
            {
                return(View(new DeliveryPlan()));
            }
            else
            {
                DeliveryPlan deliveryPlan = deliveryPlanService.GetOne(id);
                return(View(deliveryPlan));
            }
        }
Example #9
0
        static TradeCard BuildNewTradeCard()
        {
            var tradeCard = new TradeCard
            {
                OrderNumber          = "1224345",
                TradeCardType        = Schema.Common.TradeCardType.Normal,
                TradeType            = Schema.Common.TradeType.Domestic,
                SellerName           = "Minta eladó Kft.",
                SellerVatNumber      = VATNumber,
                SellerCountry        = "HU",
                SellerAddress        = "4024 Debrecen, Egyik utca 1",
                DestinationCountry   = "HU",
                DestinationAddress   = "1220 Budapest, Másik utca 1",
                DestinationName      = "Minta vevő Kft.",
                DestinationVatNumber = "12345676",
                ArrivalDate          = DateTime.Now.AddDays(1),
                ArrivalDateSpecified = true,
                LoadDate             = DateTime.Now,
                Vehicle = new Vehicle {
                    PlateNumber = "ABC123"
                }
            };
            var deliveryPlan = new DeliveryPlan
            {
                IsDestinationCompanyIdentical = false,
                LoadLocation = new Location {
                    Country = "HU", Name = "Minta eladó Kft.", VATNumber = "12345676", StreetType = "utca", City = "Debrecen", ZipCode = "4024", Street = "Minta", StreetNumber = "1"
                },
                UnloadLocation = new Location {
                    Country = "HU", Name = "Minta vevő Kft", VATNumber = "12345676", StreetType = "utca", City = "Budapest", ZipCode = "1223", Street = "Minta", StreetNumber = "1"
                }
            };
            var item = new TradeCardItemType
            {
                ProductName    = "Sajtos pogácsa",
                TradeReason    = Schema.Common.TradeReason.Sale,
                Weight         = 7500,
                Value          = 1000000,
                ValueSpecified = true,
                ProductVtsz    = "38248400",
                ItemOperation  = ItemOperation.Create
            };

            deliveryPlan.Items.Add(item);
            tradeCard.DeliveryPlans.Add(deliveryPlan);
            return(tradeCard);
        }
Example #10
0
        public DeliveryPlan GetOne(int id)
        {
            _logger.Info("Start fetch single DeliveryPlan");
            DeliveryPlan delivery = null;

            delivery = repodeliveryPlan.GetById(id);
            if (delivery == null)
            {
                _logger.Info("this category not existed");
            }
            else
            {
                _logger.Info("Got this DeliveryPlan");
            }
            _logger.Info("End fetch single DeliveryPlan");
            return(delivery);
        }
Example #11
0
        public bool Edit(DeliveryPlan deliveryPlan)
        {
            bool success;

            _logger.Info("Start Editing");
            repodeliveryPlan.Attach(deliveryPlan);
            success = (_uow.SaveChange() > 0);
            if (success == true)
            {
                _logger.Info("successfull Edited deliveryPlan");
            }
            else
            {
                _logger.Info("failed to Edit");
            }
            _logger.Info("End Edit a deliveryPlan");
            return(success);
        }
Example #12
0
        public bool Delete(DeliveryPlan deliveryPlan)
        {
            bool success;

            _logger.Info("Start deleting");
            repodeliveryPlan.Delete(deliveryPlan);
            success = _uow.SaveChange() > 0;
            if (success == true)
            {
                _logger.Info("successfull deteled deliveryPlan");
            }
            else
            {
                _logger.Info("failed to delete");
            }
            _logger.Info("End delete a deliveryPlan");
            return(success);
        }
Example #13
0
        public bool Add(DeliveryPlan deliveryPlan)
        {
            bool success;

            _logger.Info("Start add new deliveryPlan");
            repodeliveryPlan.Add(deliveryPlan);
            _logger.Info("End add new deliveryPlan");
            success = (_uow.SaveChange() > 0) ? true : false;
            if (success == true)
            {
                _logger.Info("successfull added deliveryPlan");
            }
            else
            {
                _logger.Info("failed to add");
            }
            _logger.Info("End add a list deliveryPlan deliveryPlan");
            return(success);
        }
Example #14
0
        static async Task Main(string[] args)
        {
            DistanceService dst = new DistanceService();

            // Add drone depots
            await dst.AddDepot("Depot1", "Metrostrasse 12, 40235 Düsseldorf");

            await dst.AddDepot("Depot2", "Ludenberger Str. 1, 40629 Düsseldorf");

            // Add stores
            await dst.AddStore("Store1", "Willstätterstraße 24, 40549 Düsseldorf");

            await dst.AddStore("Store2", "Bilker Allee 128, 40217 Düsseldorf");

            await dst.AddStore("Store3", "Hammer Landstraße 113, 41460 Neuss");

            await dst.AddStore("Store4", "Gladbacher Str. 471, 41460 Neuss");

            await dst.AddStore("Store5", "Lise-Meitner-Straße 1, 40878 Ratingen");

            //C1
            DeliveryPlan plan1 = await dst.Calculate("Friedrichstraße 133, 40217 Düsseldorf");

            PrintPlan(plan1);

            //C2
            DeliveryPlan plan2 = await dst.Calculate("Fischerstraße 23, 40477 Düsseldorf");

            PrintPlan(plan2);

            //C3
            DeliveryPlan plan3 = await dst.Calculate("Wildenbruchstraße 2, 40545 Düsseldorf");

            PrintPlan(plan3);

            //C4
            DeliveryPlan plan4 = await dst.Calculate("Reisholzer Str. 48, 40231 Düsseldorf");

            PrintPlan(plan4);
        }
Example #15
0
        private void AddNewStudents(IMailSender sender, Classroom classroom, List <Guid> studentIds, User loggedUser)
        {
            if (studentIds == null)
            {
                return;
            }

            var todayDeliveryPlan = classroom.DeliveryPlans.FirstOrDefault(x => x.StartDate == DateTime.Today);

            if (todayDeliveryPlan == null)
            {
                todayDeliveryPlan = new DeliveryPlan
                {
                    StartDate = DateTime.Today,
                    Classroom = classroom
                };
                _context.GetList <DeliveryPlan>().Add(todayDeliveryPlan);
                _context.Save(loggedUser);
            }

            var existingStudentIds = classroom.DeliveryPlans.SelectMany(x => x.Students).Select(x => x.Id);

            var newStudentIds = studentIds.Except(existingStudentIds);
            var newStudents   = _context.GetList <Student>().Where(a => newStudentIds.Contains(a.Id)).ToList();

            foreach (var item in newStudents)
            {
                todayDeliveryPlan.Students.Add(item);
            }
            _context.Update(todayDeliveryPlan, todayDeliveryPlan);

            // Enviar emails das aulas já disponibilizadas no dia para os novos alunos
            foreach (var classDeliveryPlan in todayDeliveryPlan.AvailableClasses)
            {
                todayDeliveryPlan.SendDeliveringClassEmail(_context, sender, classDeliveryPlan.Class, newStudents);
            }
        }
Example #16
0
        public ActionResult Create(UserViewModel viewModel)
        {
            var classroomRepository = new ClassroomRepository(_context);

            if (ModelState.IsValid)
            {
                try
                {
                    using (var tx = new TransactionScope())
                    {
                        var sender = new SmtpSender();
                        var authenticationService = new AuthenticationService(_context, sender);
                        var newStudent            = authenticationService.CreateUser(
                            viewModel.Name,
                            viewModel.Login,
                            viewModel.Email,
                            viewModel.Password,
                            Role.Student,
                            _loggedUser);

                        var classroom = classroomRepository.GetById(viewModel.ClassroomId);

                        var todayDeliveryPlan =
                            classroom.DeliveryPlans.SingleOrDefault(x => x.StartDate.Date == DateTime.Today);
                        if (todayDeliveryPlan == null)
                        {
                            todayDeliveryPlan = new DeliveryPlan
                            {
                                StartDate = DateTime.Today,
                                Classroom = classroom
                            };
                            classroom.DeliveryPlans.Add(todayDeliveryPlan);
                        }

                        todayDeliveryPlan.Students.Add((Student)newStudent);

                        var notificationService = new NotificationService(_context, sender);

                        // notify already delivered classes
                        foreach (var item in todayDeliveryPlan.AvailableClasses)
                        {
                            try
                            {
                                notificationService.SendDeliveryClassEmail(item.Class, (Student)newStudent);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        // force deliver for today
                        todayDeliveryPlan.DeliverPendingClasses(_context, new SmtpSender());

                        _context.Save(_loggedUser);
                        tx.Complete();
                    }

                    TempData["MessageType"]  = "success";
                    TempData["MessageTitle"] = Resource.StudentManagementToastrTitle;
                    TempData["Message"]      = "Student added";

                    return(Redirect(TempData["BackURL"].ToString()));
                }
                catch (Exception ex)
                {
                    TempData["MessageType"]  = "error";
                    TempData["MessageTitle"] = Resource.StudentManagementToastrTitle;
                    TempData["Message"]      = ex.Message;
                }
            }


            ViewBag.Classrooms = new SelectList(classroomRepository.ListActiveClassrooms(), "Id", "Name");
            return(View(viewModel));
        }