Beispiel #1
0
        private void AjouterVoyages()
        {
            ConsoleHelper.AfficherEntete("Nouveau Voyage");

            using (BaseDonnees context = new BaseDonnees())
            {
                var liste = new BaseDonnees().Voyages.ToList();
                ConsoleHelper.AfficherListe(liste, ListeVoyage.strategieAffichageEntitesMetier);
                var voyage = new Voyage();


                voyage.DateAller = ConsoleSaisie.SaisirDateObligatoire("Date d'aller : ");
                if (voyage.DateAller < DateTime.Today)
                {
                    ConsoleHelper.AfficherMessageErreur("Date invalide");
                    return;
                }

                voyage.DateRetour = ConsoleSaisie.SaisirDateObligatoire("Date de retour : ");
                if (voyage.DateRetour <= voyage.DateAller)
                {
                    ConsoleHelper.AfficherMessageErreur("Date invalide");
                    return;
                }

                voyage.PlacesDisponibles = ConsoleSaisie.SaisirEntierObligatoire("Places disponibles : ");
                voyage.TarifToutCompris  = ConsoleSaisie.SaisirEntierObligatoire("Tarif tout compris : ");
                voyage.IdAgenceVoyage    = ConsoleSaisie.SaisirEntierObligatoire("Id Agence de voyage : ");
                voyage.IdDestination     = ConsoleSaisie.SaisirEntierObligatoire("Id Destination : ");

                context.Voyages.Add(voyage);
                context.SaveChanges();
            }
        }
        protected void setUp()
        {
            pacific = new Voyage.Builder(new VoyageNumber("4567"), L.SHANGHAI)
                      .addMovement(L.LONGBEACH, new DateTime(1), new DateTime(2))
                      .build();

            transcontinental = new Voyage.Builder(new VoyageNumber("4567"), L.LONGBEACH)
                               .addMovement(L.CHICAGO, new DateTime(1), new DateTime(2))
                               .addMovement(L.NEWYORK, new DateTime(3), new DateTime(4))
                               .build();

            atlantic = new Voyage.Builder(new VoyageNumber("4556"), L.NEWYORK)
                       .addMovement(L.ROTTERDAM, new DateTime(1), new DateTime(2))
                       .addMovement(L.GOTHENBURG, new DateTime(3), new DateTime(4))
                       .build();

            voyage = new Voyage.Builder(new VoyageNumber("0123"), L.SHANGHAI)
                     .addMovement(L.ROTTERDAM, new DateTime(1), new DateTime(2))
                     .addMovement(L.GOTHENBURG, new DateTime(3), new DateTime(4))
                     .build();

            wrongVoyage = new Voyage.Builder(new VoyageNumber("666"), L.NEWYORK)
                          .addMovement(L.STOCKHOLM, new DateTime(1), new DateTime(2))
                          .addMovement(L.HELSINKI, new DateTime(3), new DateTime(4))
                          .build();
        }
Beispiel #3
0
        public void Voyage_CalculateNumberOfStopsForStarship_DistanceTillRefuelHasValue_NumberOfStopsReturned()
        {
            // Arrange
            var distanceToTravel = 1000000;

            var starshipA = new Starship()
            {
                Consumables = "1 year",
                MegaLights  = "75"
            };

            var starshipB = new Starship()
            {
                Consumables = "8 weeks",
                MegaLights  = "50"
            };

            // Act
            var voyageA = new Voyage(starshipA);
            var voyageB = new Voyage(starshipB);

            // Assert
            Assert.AreEqual(1, voyageA.CalculateNumberOfStopsForStarship(distanceToTravel));
            Assert.AreEqual(14, voyageB.CalculateNumberOfStopsForStarship(distanceToTravel));
        }
Beispiel #4
0
        public static List <Voyage> RecupererVoyage(string nomDeFichier)
        {
            var listeVoyage = new List <Voyage>();

            if (File.Exists(nomDeFichier))
            {
                var lignes = File.ReadAllLines(nomDeFichier);

                foreach (var ligne in lignes)
                {
                    string[] champs         = ligne.Split(';');
                    var      nomDestination = champs[0];
                    var      destination    = Données.Destinations.Where(x => x.Région == nomDestination).FirstOrDefault();
                    var      voyage         = new Voyage
                    {
                        Destination       = destination,
                        DateAller         = DateTime.Parse(champs[1]),
                        DateRetour        = DateTime.Parse(champs[2]),
                        NombreVoyageurMax = int.Parse(champs[3]),
                    };

                    listeVoyage.Add(voyage);
                }
            }
            return(listeVoyage);
        }
Beispiel #5
0
        private void NouveauVoyage()
        {
            ConsoleHelper.AfficherEntete("Nouveau Voyage");
            OutilsConsole.CentrerTexte("LISTE DES DESTINATIONS\n ");
            ConsoleHelper.AfficherListe(new DestinationData().GetList(), strategieAffichageDestination);

            var voyage = new Voyage
            {
                DestinationId     = ConsoleSaisie.SaisirEntierObligatoire("Id de la Destination retenue ?"),
                DateAller         = ConsoleSaisie.SaisirDateObligatoire("Date Aller ?"),
                DateRetour        = ConsoleSaisie.SaisirDateObligatoire("Date Retour ?"),
                PlacesDisponibles = ConsoleSaisie.SaisirEntierObligatoire("Places max disponibles ?"),
                PrixParPersonne   = ConsoleSaisie.SaisirDecimalObligatoire("Prix/pers. ?"),
                AgenceVoyageId    = ConsoleSaisie.SaisirEntierObligatoire("Id de l'Agence de Voyage (par défaut 1) ?")
            };
            var voyageService = new VoyageService();

            voyageService.Ajout(voyage);
            if (voyage.Id != 0)
            {
                Console.WriteLine("Le Voyage a été enregistré avec succès");
            }
            else
            {
                Console.WriteLine("Le Voyage n'a pas pu être créé (Erreur de date ou de destination ...)");
            }
        }
 private Leg ToLeg(Voyage voyage, TransitEdge first, TransitEdge last)
 {
     return(new Leg(voyage, _locatinRepository.Find(new UnLocode(first.From)),
                    first.FromDate,
                    _locatinRepository.Find(new UnLocode(last.To)),
                    last.ToDate));
 }
        public List <Inscription> GetTrainAnnounces(int pTrainId)
        {
            Voyage             leVoyage        = context.GetAll <Voyage>().FirstOrDefault(v => v.numeroTrain == pTrainId);
            List <Inscription> lesInscriptions = context.GetAll <Inscription>().ToList().Where(i => i.idVoyage == leVoyage.idVoyage).ToList();

            return(lesInscriptions);
        }
Beispiel #8
0
        private void Nouveau()
        {
            ConsoleHelper.AfficherEntete("Nouveau");

            try
            {
                var voyage = new Voyage
                             (
                    dateAller: ConsoleSaisie.SaisirDateObligatoire("Date Aller : "),
                    dateRetour: ConsoleSaisie.SaisirDateObligatoire("Date Retour : "),
                    placesDisponibles: ConsoleSaisie.SaisirEntierObligatoire("Places Disponibles : "),
                    prixParPersonne: ConsoleSaisie.SaisirDecimalObligatoire("Prix Par Personne : "),
                    idDestination: ConsoleSaisie.SaisirEntierObligatoire("Destination (ID) : "),
                    idAgenceVoyage: ConsoleSaisie.SaisirEntierObligatoire("Agence de voyage (ID) : ")
                             );

                ServiceVoyage service = new ServiceVoyage();
                service.AjouterVoyage(voyage);
                ConsoleHelper.AfficherLibelleSaisie("Voyage ajouté !");
            }
            catch
            {
                ConsoleHelper.AfficherMessageErreur("Problème lors de l'ajout du Voyage !");
            }
        }
Beispiel #9
0
 public void VerifierVoyage_DateRetour(Voyage voyage)
 {
     if (voyage.DateRetour < voyage.DateAller)
     {
         throw new MetierException("ATTENTION!! La date de retour ne doit pas être antérieure à la date de départ ");
     }
 }
        public ActionResult TicketСlearance(int?id)
        {
            if (id == null || id == 0)
            {
                return(View("Error"));
            }
            Voyage voyage = db.Voyages.FirstOrDefault(v => v.Id == id);

            if (voyage != null)
            {
                var allnumberOfSeats = Enumerable.Range(1, voyage.NumberOfSeats).ToList();

                var freeSeats =
                    allnumberOfSeats.Except(db.Voyages.Where(v => v.Id == id).SelectMany(v => v.Orders.Select(order => order.Ticket.PassengerSeatNumber).ToList()));
                ViewBag.Voyage     = id;
                ViewBag.Name       = voyage.Name;
                ViewBag.Number     = voyage.Number;
                ViewBag.TicketCost = voyage.OneTicketCost;
                var selectListItems = freeSeats.Select(i => new SelectListItem {
                    Value = i.ToString(), Text = i.ToString()
                }).ToList();
                ViewBag.SelectSeatNumber = selectListItems;
            }
            return(View("TicketСlearance"));
        }
Beispiel #11
0
        public Boolean CreateVoyage(Voyage voyage)
        {
            if (!ModelState.IsValid)
            {
                return(false);
            }
            string idUser = User.Identity.GetUserId();

            voyage.ListeVoyageur = new List <ApplicationUser> {
                db.Users.Find(idUser)
            };
            voyage.BudgetRestant = voyage.Budget;
            voyage.Jours         = new List <Jour>();
            for (int i = 0; i < voyage.NbJours; i++)
            {
                Jour a = new Jour();
                a.ListeActivite = new List <Activite>();
                a.VoyageId      = voyage.VoyageId;
                voyage.Jours.Add(a);
            }
            voyage.Transport = new List <Transport>();
            db.Voyages.Add(voyage);
            db.SaveChanges();

            return(true);
        }
Beispiel #12
0
        public async Task <ActionResult <Voyage> > PostVoyage(Voyage voyage)
        {
            ApplicationUser connectedUser = await _userManager.GetUserAsync(User);

            voyage.MyUser = connectedUser;

            _context.Voyage.Add(voyage);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (VoyageExists(voyage.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetVoyage", new { id = voyage.Id }, voyage));
        }
Beispiel #13
0
 public ActionResult SaveVoyage(Voyage value)
 {
     ViewBag.Title         = "Ajout de vehicule";
     ViewBag.postInfo      = "Company saved successfuly";
     ViewBag.postInfoClass = "alert-success";
     Console.WriteLine(value.Id + ";" + value.DepartId + ";" + value.ArrivalId + ";" + value.DepartTime + ";" + value.ArrivalTime + ";" + value.CompanyId);
     if (!ModelState.IsValid)
     {
         var errors = ModelState.Values.SelectMany(v => v.Errors);
         ViewBag.postInfo = errors;
         foreach (var v in errors)
         {
             Console.WriteLine("Error" + v.ErrorMessage);
         }
         ViewBag.postInfoClass = "alert-danger";
     }
     else
     {
         using (var dao = new Dao.Dao())
         {
             dao.InsertVoyage(value);
         }
     }
     return(View("Saved"));
 }
Beispiel #14
0
        public async Task <IActionResult> PostVoyage([FromBody] Voyage voyage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Voyage.Add(voyage);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (VoyageExists(voyage.VoyageId))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetVoyage", new { id = voyage.VoyageId }, voyage));
        }
Beispiel #15
0
 public void VerifierVoyage_PlaceDispo(Voyage voyage)
 {
     if (voyage.PlacesDispo == 0)
     {
         throw new MetierException("Voyage complet!!");
     }
 }
Beispiel #16
0
        public HandlingEvent(Cargo cargo,
                             DateTime completionTime,
                             DateTime registrationTime,
                             HandlingType type,
                             Location location)
        {
            Validate.NotNull(cargo, "Cargo is required");
            Validate.NotNull(completionTime, "Completion time is required");
            Validate.NotNull(registrationTime, "Registration time is required");
            Validate.NotNull(type, "Handling event type is required");
            Validate.NotNull(location, "Location is required");

            if (type.RequiresVoyage())
            {
                throw new ArgumentException("Voyage is required for event type " + type);
            }

            this.completionTime   = completionTime;
            this.registrationTime = registrationTime;
            this.type             = type;
            this.locationId       = location.id;
            this.cargoId          = cargo.id;
            this.location         = location;
            this.cargo            = cargo;
            voyage = null;
        }
Beispiel #17
0
        protected void setUp()
        {
            pacific = new Voyage.Builder(new VoyageNumber("4567"), L.SHANGHAI)
                .addMovement(L.LONGBEACH, new DateTime(1), new DateTime(2))
                .build();

            transcontinental = new Voyage.Builder(new VoyageNumber("4567"), L.LONGBEACH)
                .addMovement(L.CHICAGO, new DateTime(1), new DateTime(2))
                .addMovement(L.NEWYORK, new DateTime(3), new DateTime(4))
                .build();

            atlantic = new Voyage.Builder(new VoyageNumber("4556"), L.NEWYORK)
                .addMovement(L.ROTTERDAM, new DateTime(1), new DateTime(2))
                .addMovement(L.GOTHENBURG, new DateTime(3), new DateTime(4))
                .build();

            voyage = new Voyage.Builder(new VoyageNumber("0123"), L.SHANGHAI)
                .addMovement(L.ROTTERDAM, new DateTime(1), new DateTime(2))
                .addMovement(L.GOTHENBURG, new DateTime(3), new DateTime(4))
                .build();

            wrongVoyage = new Voyage.Builder(new VoyageNumber("666"), L.NEWYORK)
                .addMovement(L.STOCKHOLM, new DateTime(1), new DateTime(2))
                .addMovement(L.HELSINKI, new DateTime(3), new DateTime(4))
                .build();
         }
        public IHttpActionResult PutVoyage(int id, Voyage voyage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != voyage.ID)
            {
                return(BadRequest());
            }

            db.Entry(voyage).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VoyageExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #19
0
        protected void Ajouter_Click(object sender, EventArgs e)
        {
            int      idConducteur = int.Parse(drDownConducteur.SelectedItem.Value);
            string   depart       = txtDepart.Text;
            string   destination  = txtDestination.Text;
            int      nbPassagers;
            bool     isNbPassagersDigit = int.TryParse(txtNbPassagers.Text, out nbPassagers);
            double   prix;
            bool     isPrixDigit = double.TryParse(txtPrix.Text, out prix);
            DateTime heureDepart = calHeureDepart.SelectedDate;
            bool     fumeur      = ckBoxFumeur.Checked;
            bool     animaux     = ckBoxAnimaux.Checked;
            bool     bcpBagages  = ckBoxBcpBagage.Checked;

            if (isPrixDigit && isNbPassagersDigit)
            {
                Voyage voyage = new Voyage(0, idConducteur, prix, depart, destination, heureDepart, animaux, fumeur, bcpBagages, nbPassagers);
                VoyageFactory.Save(ConfigurationManager.ConnectionStrings["cnnStr"].ConnectionString, voyage);
                Response.Redirect("Default.aspx");
            }
            else
            {
                lblEnterNumber.Visible = true;
            }
        }
Beispiel #20
0
        /// <summary>
        /// A new itinerary which is a copy of the old one, adjusted for the delay of the given voyage.
        /// </summary>
        /// <param name="rescheduledVoyage">the voyage that has been rescheduled</param>
        /// <returns>A new itinerary which is a copy of the old one, adjusted for the delay of the given voyage.</returns>
        public Itinerary WithRescheduledVoyage(Voyage rescheduledVoyage)
        {
            var newLegsList = new List <Leg>(Legs.Count());

            Leg lastAdded = null;

            foreach (var leg in Legs)
            {
                if (leg.Voyage.sameAs(rescheduledVoyage))
                {
                    var modifiedLeg = leg.WithRescheduledVoyage(rescheduledVoyage);

                    // This truncates the itinerary if the voyage rescheduling makes
                    // it impossible to maintain the old unload-load chain.
                    if (lastAdded != null && modifiedLeg.LoadTime < lastAdded.UnloadTime)
                    {
                        break;
                    }

                    newLegsList.Add(modifiedLeg);
                }
                else
                {
                    newLegsList.Add(leg);
                }
                lastAdded = leg;
            }

            return(new Itinerary(newLegsList));
        }
Beispiel #21
0
        public async Task <IActionResult> PutVoyage([FromRoute] long id, [FromBody] Voyage voyage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != voyage.VoyageId)
            {
                return(BadRequest());
            }

            _context.Entry(voyage).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VoyageExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #22
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="cargo">cargo</param>
        /// <param name="completionTime">completion time, the reported time that the event actually happened (e.g. the receive took place).</param>
        /// <param name="registrationTime">registration time, the time the message is received</param>
        /// <param name="type">type of event</param>
        /// <param name="location">where the event took place</param>
        /// <param name="voyage">the voyage</param>
        /// <param name="operatorCode">operator code for port operator</param>
        internal HandlingEvent(Cargo cargo,
                               DateTime completionTime,
                               DateTime registrationTime,
                               HandlingActivityType type,
                               Location location,
                               Voyage voyage,
                               OperatorCode operatorCode)
        {
            Validate.notNull(cargo, "Cargo is required");
            Validate.notNull(location, "Location is required");
            Validate.notNull(voyage, "Voyage is required");
            Validate.notNull(operatorCode, "Operator code is required");

            if (!type.isVoyageRelated())
            {
                throw new ArgumentException("Voyage is not allowed with event type " + type);
            }

            SequenceNumber   = EventSequenceNumber.Next();
            Cargo            = cargo;
            CompletionTime   = completionTime;
            RegistrationTime = registrationTime;
            Activity         = new HandlingActivity(type, location, voyage);
            OperatorCode     = operatorCode;
        }
Beispiel #23
0
        //Fonction permettant d'ajouter un voyage
        public void AjouterVoyage(Voyage UnVoyage)
        {
            try
            {
                // Ouverture de la connexion SQL
                bdd.connection.Open();

                // Création d'une commande SQL en fonction de l'objet connection
                MySqlCommand cmd = bdd.connection.CreateCommand();

                // Requête SQL pour vérifier sur le Vol existe réellement
                cmd.CommandText = "INSERT INTO voyage (libelle, escale) VALUES (@libelle, @escale)";

                // utilisation de l'objet contact passé en paramètre
                cmd.Parameters.AddWithValue("@libelle", UnVoyage.Libelle);
                cmd.Parameters.AddWithValue("@escale", UnVoyage.Is_Escale);
                // Exécution de la commande SQL
                cmd.ExecuteNonQuery();
                // Fermeture de la connexion
                bdd.connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Convert.ToString(ex));
            }
        }
Beispiel #24
0
        /// <summary>
        /// Сгенерировать случайные рейсы в xml
        /// </summary>
        /// <param name="Count">количество рейсов</param>
        public static void CreateVoyagesXML(int Count)
        {
            var rnd = new Random();

            try
            {
                //генерируем рейсы
                var            startDate = DateTime.Now.AddHours(-1);
                Model.Voyage[] voyages   = new Model.Voyage[Count];
                for (int i = 0; i < Count; i++)
                {
                    var rndplane  = Services.RandomPlane(rnd);
                    var startCity = Services.RandomCity("", rnd);
                    voyages[i] = new Voyage
                                 (
                        Services.RandomString(6, rnd),
                        rndplane,
                        startCity,
                        Services.RandomCity(startCity, rnd),
                        startDate = Services.RandomDate(startDate, rnd, true),
                        startDate = Services.RandomDate(startDate, rnd, false),
                        rnd.Next(1, rndplane.Capacity)
                                 );
                }

                XmlSerializer formatter = new XmlSerializer(typeof(Model.Voyage[]));

                using (System.IO.FileStream fs = new System.IO.FileStream("voyages.xml", System.IO.FileMode.Create))
                {
                    formatter.Serialize(fs, voyages);
                }
            }
            catch (Exception) { }
        }
Beispiel #25
0
        public IHttpActionResult PostVoyage(Voyage voyage)
        {
            string id = User.Identity.GetUserId();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            int lenght = voyage.NbDeJour;

            for (int i = 0; i < lenght; i++)
            {
                Jour temp = new Jour();
                temp.Voyage        = voyage;
                temp.Date          = voyage.DateTimeDebut.AddDays(i);
                temp.BudgetJournee = 0;
                db.Jours.Add(temp);
                voyage.Jours.Add(temp);
            }

            /*ApplicationUser user = db.Users.FirstOrDefault(u => u.Id == id);
             *
             * voyage.ApplicationUsers.Add(db.Users.FirstOrDefault(u => u.Id == id));*/

            db.Voyages.Add(voyage);
            db.SaveChanges();

            VoyageDTO dto = new VoyageDTO(voyage);

            return(Ok(dto));
        }
Beispiel #26
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="cargo">cargo</param>
        /// <param name="completionTime">completion time, the reported time that the event actually happened (e.g. the receive took place).</param>
        /// <param name="registrationTime">registration time, the time the message is received</param>
        /// <param name="eventType">type of event</param>
        /// <param name="location">where the event took place</param>
        /// <param name="voyage">the voyage</param>
        public HandlingEvent(Cargo cargo,
                             DateTime completionTime,
                             DateTime registrationTime,
                             HandlingType eventType,
                             Location location,
                             Voyage voyage)
        {
            Validate.NotNull(cargo, "Cargo is required");
            Validate.NotNull(completionTime, "Completion time is required");
            Validate.NotNull(registrationTime, "Registration time is required");
            Validate.NotNull(eventType, "Handling event eventType is required");
            Validate.NotNull(location, "Location is required");
            Validate.NotNull(voyage, "Voyage is required");

            if (eventType.ProhibitsVoyage())
            {
                throw new ArgumentException("Voyage is not allowed with event eventType " + eventType);
            }

            this.voyage           = voyage;
            this.completionTime   = completionTime;
            this.registrationTime = registrationTime;
            type          = eventType;
            this.location = location;
            this.cargo    = cargo;
        }
Beispiel #27
0
 protected void Page_Load(object sender, EventArgs e)
 {
     membre = Session[TP3.SESSIONMEMBRE] as Membre;
     if (membre != null)
     {
         if (membre.IsAdmin)
         {
             btnDelete.Visible = true;
         }
     }
     if (Request.QueryString["ID"] != null)
     {
         ID = int.Parse(Request.QueryString["ID"]);
     }
     else
     {
         Response.Redirect("Default.aspx");
     }
     voyage              = VoyageFactory.GetByID(System.Configuration.ConfigurationManager.ConnectionStrings["cnnStr"].ConnectionString, ID);
     lblPrix.Text        = voyage.Prix.ToString();
     lblDepart.Text      = voyage.Depart;
     lblDestination.Text = voyage.Destination;
     lblHeure.Text       = voyage.HeureDepart.ToString();
     lblPassagers.Text   = voyage.NbPassagers.ToString();
     chkAnimaux.Checked  = voyage.Animaux;
     chkFumeur.Checked   = voyage.Fumeur;
     chkEquipe.Checked   = voyage.BienEquipe;
 }
        public async Task <IActionResult> Edit(int id, [Bind("Id,IdDestination,DateDepart,DateRetour,PlacesDispo,PrixHt,Reduction,Descriptif")] Voyage voyage)
        {
            if (id != voyage.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(voyage);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!VoyageExists(voyage.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["IdDestination"] = new SelectList(_context.Destination, "Id", "Nom", voyage.IdDestination);
            return(View(voyage));
        }
Beispiel #29
0
        public void AddVoyages()
        {
            if (_voyageRepository.GetAll().Any())
            {
                return;
            }
            var d1 = _personRepository.Single(p => p.FirstName == "Homer");
            var d2 = _personRepository.Single(p => p.FirstName == "Marge");

            _logger.LogWarning("Voyages added");

            #region 3 voyages random
            var v1 = new Voyage()
            {
                StartPlace    = "EverGreen Terrace",
                EndPlace      = "School",
                Seat          = 4,
                RemainingSeat = 2,
                Comment       = "Let's Go",
                Driver        = (Driver)d2,
                StartTime     = DateTime.Now
            };
            var v2 = new Voyage()
            {
                StartPlace    = "EverGreen Terrace",
                EndPlace      = "Moe's'",
                Seat          = 4,
                RemainingSeat = 0,
                Comment       = "I love beer",
                Driver        = (Driver)d1,
                StartTime     = DateTime.Now.AddHours(2)
            };
            var v3 = new Voyage()
            {
                StartPlace    = "Kwik e Mart",
                EndPlace      = "EverGreen Terrace",
                Seat          = 4,
                RemainingSeat = 3,
                Comment       = "Let's buy a squishy",
                Driver        = (Driver)d2,
                StartTime     = DateTime.Now.AddDays(1)
            };
            var v4 = new Voyage()
            {
                StartPlace    = "SpringField",
                EndPlace      = "Ney-York",
                Seat          = 4,
                RemainingSeat = 0,
                Comment       = "The City of New York vs. Homer Simpson",
                Driver        = (Driver)d2,
                StartTime     = new DateTime(1997, 9, 21, 12, 12, 00),
                Archived      = true
            };
            #endregion
            _voyageRepository.UpdateRange(v1, v2, v3);
            _voyageRepository.Save();

            _logger.LogWarning("Voyages added");
        }
Beispiel #30
0
 /// <summary>
 /// Creates new leg instance.
 /// </summary>
 /// <param name="voyage">Voyage</param>
 /// <param name="loadLocation">Location where cargo is supposed to be loaded.</param>
 /// <param name="loadDate">Date and time when cargo is supposed to be loaded</param>
 /// <param name="unloadLocation">Location where cargo is supposed to be unloaded.</param>
 /// <param name="unloadDate">Date and time when cargo is supposed to be unloaded.</param>
 public Leg(Voyage.Voyage voyage, Location.Location loadLocation, DateTime loadDate, Location.Location unloadLocation, DateTime unloadDate)
 {
    _loadLocation = loadLocation;
    _voyage = voyage;
    _unloadDate = unloadDate;
    _unloadLocation = unloadLocation;
    _loadDate = loadDate;
 }
        public ActionResult Publish(int Id)
        {
            Voyage pendingVoyage = db.Voyages.Find(Id);

            pendingVoyage.IsPending = true;
            db.SaveChanges();
            return(RedirectToAction("Details", "Voyages", new { id = Id }));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            Voyage voyage = db.Voyages.Find(id);

            db.Voyages.Remove(voyage);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public IEnumerable<Cargo> findCargosOnVoyage(Voyage voyage)
 {
     return sessionFactory.GetCurrentSession().CreateQuery(
       "select cargo from Cargo as cargo " +
         "left join cargo.Itinerary.Legs as leg " +
         "where leg.Voyage = :voyage").
       SetParameter("voyage", voyage).
       List<Cargo>();
 }
        protected void SetUp()
        {
            events = new List<HandlingEvent>();

            voyage = new Voyage.Builder(new VoyageNumber("0123"), SampleLocations.STOCKHOLM).
                AddMovement(SampleLocations.HAMBURG, DateTime.Now, DateTime.Now).
                AddMovement(SampleLocations.HONGKONG, DateTime.Now, DateTime.Now).
                AddMovement(SampleLocations.MELBOURNE, DateTime.Now, DateTime.Now).
                Build();
        }
		/// <summary>
		/// Creates an instance of <see cref="HandlingActivity"/> from the handling event type and the location.
		/// </summary>
		/// <param name="eventType">The handling event type.</param>
		/// <param name="location">The location where the handling is done.</param>
		/// <param name="voyage"></param>
		public HandlingActivity(HandlingEventType eventType, Location.Location location, Voyage.Voyage voyage)
		{
			if (location == null)
				throw new ArgumentNullException("location");
			if (voyage == null)
				throw new ArgumentNullException("voyage");

			_eventType = eventType;
			_location = location;
			_voyage = voyage;
		}
        protected void SetUp()
        {
            voyage = new Voyage.Builder(new VoyageNumber("0123"), SampleLocations.SHANGHAI).
                AddMovement(SampleLocations.ROTTERDAM, dateTime, dateTime).
                AddMovement(SampleLocations.GOTHENBURG, dateTime, dateTime).
                Build();

            wrongVoyage = new Voyage.Builder(new VoyageNumber("666"), SampleLocations.NEWYORK).
                AddMovement(SampleLocations.STOCKHOLM, dateTime, dateTime).
                AddMovement(SampleLocations.HELSINKI, dateTime, dateTime).
                Build();
        }
        public IEnumerable<Cargo> findCargosOnVoyage(Voyage voyage)
        {
            var onVoyage = new List<Cargo>();
            foreach(Cargo cargo in cargoDb.Values)
            {
                if(voyage.sameAs(cargo.CurrentVoyage))
                {
                    onVoyage.Add(cargo);
                }
            }

            return onVoyage;
        }
        protected void SetUp()
        {
            cargo = new Cargo(new TrackingId("ABC"), new RouteSpecification(SampleLocations.SHANGHAI, SampleLocations.DALLAS, DateTime.Parse("2009-04-01")));
            voyage = new Voyage.Builder(new VoyageNumber("X25"), SampleLocations.HONGKONG).
              AddMovement(SampleLocations.SHANGHAI, new DateTime(), new DateTime()).
              AddMovement(SampleLocations.DALLAS, new DateTime(), new DateTime()).
              Build();
            event1 = new HandlingEvent(cargo, DateTime.Parse("2009-03-05"), new DateTime(100), HandlingType.LOAD, SampleLocations.SHANGHAI, voyage);
            event1duplicate = new HandlingEvent(cargo, DateTime.Parse("2009-03-05"), new DateTime(200), HandlingType.LOAD, SampleLocations.SHANGHAI, voyage);
            event2 = new HandlingEvent(cargo, DateTime.Parse("2009-03-10"), new DateTime(150), HandlingType.UNLOAD, SampleLocations.DALLAS, voyage);

            handlingHistory = new HandlingHistory(new List<HandlingEvent>{event2, event1, event1duplicate});
        }
        private void AssertHandlingEvent(Cargo cargo, HandlingEvent evnt, HandlingType expectedEventType,
                                         Location expectedLocation, int completionTimeMs, int registrationTimeMs,
                                         Voyage voyage)
        {
            Assert.AreEqual(expectedEventType, evnt.Type);
            Assert.AreEqual(expectedLocation, evnt.Location);

            DateTime expectedCompletionTime = SampleDataGenerator.Offset(completionTimeMs);
            Assert.AreEqual(expectedCompletionTime, evnt.CompletionTime);

            DateTime expectedRegistrationTime = SampleDataGenerator.Offset(registrationTimeMs);
            Assert.AreEqual(expectedRegistrationTime, evnt.RegistrationTime);

            Assert.AreEqual(voyage, evnt.Voyage);
            Assert.AreEqual(cargo, evnt.Cargo);
        }
Beispiel #40
0
        public Offhire CreateOffhire(
            long referenceNumber,
            DateTime startDateTime,
            DateTime endDateTime,
            Company introducer,
            VesselInCompany vesselInCompany,
            Voyage voyage,
            ActivityLocation offhireLocation,
            DateTime voucherDate,
            Currency voucherCurrency)
        {
            var offhire = new Offhire(
                referenceNumber,
                startDateTime,
                endDateTime,
                introducer,
                vesselInCompany,
                voyage,
                offhireLocation,
                voucherDate,
                voucherCurrency,
                this.offhireDomainService,
                this.offhireManagementSystemDomainService,
                this.vesselDomainService,
                this.voyageDomainService,
                this.companyDomainService,
                this.activityLocationDomainService,
                this.currencyDomainService);

            var init = this.workflowRepository.Single(c => c.WorkflowEntity == WorkflowEntities.Offhire && c.CurrentWorkflowStage == WorkflowStages.Initial);
            if (init == null)
                throw new ObjectNotFound("OffhireInitialStep");

            var offhireWorkflow = new OffhireWorkflowLog(offhire, WorkflowEntities.Offhire, DateTime.Now, WorkflowActions.Init,
                //TODO: Fake ActorId
                    1101, "", init.Id, true);

            offhire.ApproveWorkflows.Add(offhireWorkflow);

            offhireConfigurator.Configure(offhire);

            return offhire;
        }
Beispiel #41
0
		/// <summary>
		/// Creates new leg instance.
		/// </summary>
		/// <param name="voyage"></param>
		/// <param name="loadLocation">Location where cargo is supposed to be loaded.</param>
		/// <param name="loadDate">Date and time when cargo is supposed to be loaded.</param>
		/// <param name="unloadLocation">Location where cargo is supposed to be unloaded.</param>
		/// <param name="unloadDate">Date and time when cargo is supposed to be unloaded.</param>
		public Leg(Voyage.Voyage voyage, Location.Location loadLocation, DateTime loadDate, Location.Location unloadLocation, DateTime unloadDate)
		{
			if (voyage == null)
				throw new ArgumentNullException("voyage", "The voyage cannot be null");
			if (loadLocation == null)
				throw new ArgumentNullException("loadLocation", "The load location cannot be null");
			if (unloadLocation == null)
				throw new ArgumentNullException("unloadLocation", "The unload location cannot be null");
			if (loadDate == default(DateTime))
				throw new ArgumentException("The load date is not correct.", "loadDate");
			if (unloadDate == default(DateTime))
				throw new ArgumentException("The unloadDate date is not correct.", "unloadDate");

			_voyage = voyage;
			_loadLocation = loadLocation;
			_unloadDate = unloadDate;
			_unloadLocation = unloadLocation;
			_loadDate = loadDate;
		}
        public void setupCargo()
        {
            TrackingIdFactoryInMem trackingIdFactory = new TrackingIdFactoryInMem();

            // Creating new voyages to avoid rescheduling shared ones, breaking other tests
            voyage1 = new Voyage(new VoyageNumber("V1"), V.HONGKONG_TO_NEW_YORK.Schedule);
            voyage2 = new Voyage(new VoyageNumber("V2"), V.NEW_YORK_TO_DALLAS.Schedule);
            voyage3 = new Voyage(new VoyageNumber("V3"), V.DALLAS_TO_HELSINKI.Schedule);

            TrackingId trackingId = trackingIdFactory.nextTrackingId();
            RouteSpecification routeSpecification = new RouteSpecification(L.HANGZOU,
                L.STOCKHOLM,
                DateTime.Parse("2008-12-23"));

            cargo = new Cargo(trackingId, routeSpecification);
            Itinerary itinerary = new Itinerary(Leg.DeriveLeg(voyage1, L.HANGZOU, L.NEWYORK),
                Leg.DeriveLeg(voyage2, L.NEWYORK, L.DALLAS),
                Leg.DeriveLeg(voyage3, L.DALLAS, L.STOCKHOLM));
            cargo.AssignToRoute(itinerary);
        }
Beispiel #43
0
        /// <summary>
        /// retrieves brand detail
        /// </summary>
        /// <param name="voyage">brand attribute</param>
        /// <returns>Brand entity</returns>
        private static Voyage MapAsync(Entities.Voyage voyage)
        {
            var voyageData = new Voyage();
            voyageData.DebarkDate = voyage.DebarkDate;
            voyageData.Name = voyage.Name;
            voyageData.DebarkPortId = voyage.DebarkPortId;
            voyageData.DestinationId = voyage.DestinationId;
            voyageData.EmbarkDate = voyage.EmbarkDate;
            voyageData.EmbarkPortId = voyage.EmbarkPortId;
            voyageData.IsActive = voyage.IsActive;
            voyageData.AssignItineraries(voyage.Itineraries);
            voyageData.Nights = voyage.Nights;
            voyageData.Number = voyage.Number;
            voyageData.ShipId = voyage.ShipId;
            voyageData.VoyageId = voyage.VoyageId;
            var mediaItems = voyage.MediaItems.FirstOrDefault();
            voyageData.MediaItemAddress = mediaItems != null ? mediaItems.MediaItemAddress : string.Empty;

            return voyageData;
        }
        protected void setUp()
        {
            cargo = new Cargo(new TrackingId("ABC"),
                new RouteSpecification(L.SHANGHAI, L.DALLAS, DateTime.Parse("2009-04-01")));
            cargo2 = new Cargo(new TrackingId("DEF"),
                new RouteSpecification(L.SHANGHAI, L.NEWYORK, DateTime.Parse("2009-04-15")));

            voyage =
                new Voyage.Builder(new VoyageNumber("X25"), L.HONGKONG).addMovement(L.SHANGHAI,
                    new DateTime(1),
                    new DateTime(2)).addMovement(L.DALLAS, new DateTime(3), new DateTime(4)).build();
            event1 = new HandlingEvent(cargo,
                DateTime.Parse("2009-03-05"),
                DateTime.Parse("2009-03-05"),
                HandlingActivityType.LOAD,
                L.SHANGHAI,
                voyage,
                new OperatorCode("ABCDE"));
            event1duplicate = new HandlingEvent(cargo,
                DateTime.Parse("2009-03-05"),
                DateTime.Parse("2009-03-07"),
                HandlingActivityType.LOAD,
                L.SHANGHAI,
                voyage,
                new OperatorCode("ABCDE"));
            event2 = new HandlingEvent(cargo,
                DateTime.Parse("2009-03-10"),
                DateTime.Parse("2009-03-06"),
                HandlingActivityType.UNLOAD,
                L.DALLAS,
                voyage,
                new OperatorCode("ABCDE"));
            eventOfCargo2 = new HandlingEvent(cargo2,
                DateTime.Parse("2009-03-11"),
                DateTime.Parse("2009-03-08"),
                HandlingActivityType.LOAD,
                L.GOTHENBURG,
                voyage,
                new OperatorCode("ABCDE"));
        }
		/// <summary>
		/// Creates new event.
		/// </summary>
		/// <param name="eventType">Type of the event.</param>
		/// <param name="location">The location where the event took place.</param>
		/// <param name="registrationDate">Registration time, the time the message is received.</param>
		/// <param name="completionDate">Completion time, the reported time that the event actually happened (e.g. the receive took place).</param>
		/// <param name="cargo">Cargo.</param>
		/// <param name="voyage">The voyage.</param>
		public HandlingEvent(HandlingEventType eventType, Location.Location location, DateTime registrationDate, DateTime completionDate, Cargo.Cargo cargo, Voyage.Voyage voyage)
		{
			if (cargo == null)
				throw new ArgumentNullException("cargo", "Cargo is required.");
			if (location == null)
				throw new ArgumentNullException("location", "Location is required.");
			if (voyage == null)
				throw new ArgumentNullException("voyage", "Voyage is required.");
			if (registrationDate == default(DateTime))
				throw new ArgumentException("The registration date is required.", "registrationDate");
			if (completionDate == default(DateTime))
				throw new ArgumentException("The completion date is required.", "completionDate");

			if (eventType.ProhibitsVoyage())
				throw new ArgumentException("Voyage is not allowed with event type : " + eventType, "eventType");

			_eventType = eventType;
			_completionDate = completionDate;
			_registrationDate = registrationDate;
			_location = location;
			_cargo = cargo;
			_voyage = voyage;
		}
        /// <summary>
        /// Maps the voyage data.
        /// </summary>
        /// <param name="voyageData">The voyage data.</param>
        /// <returns>voyage data</returns>
        private async Task<ICollection<Voyage>> MapVoyageData(ICollection<Voyage> voyageData)
        {
            var portData = new ListResult<Port>();
            string portIds = string.Empty;

            foreach (var voyages in voyageData)
            {
                if (voyages.Itineraries != null && voyages.Itineraries.Count > 0)
                {
                    foreach (var itenarary in voyages.Itineraries)
                    {
                        if (!string.IsNullOrEmpty(itenarary.PortId))
                        {
                            portIds += itenarary.PortId + CommaSeparator;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(portIds))
            {
                portData = await this.referenceDataRepository.ListPortAsync(portIds.Substring(0, portIds.Length - 1));
            }

            if (portData == null || portData.Items.Count == 0)
            {
                return voyageData;
            }

            var voyageResult = new List<Voyage>();

            foreach (var voyages in voyageData)
            {
                var voyage = new Voyage();
                voyage.EmbarkDate = voyages.EmbarkDate;
                voyage.IsActive = voyages.IsActive;
                voyage.Name = voyages.Name;
                voyage.Number = voyages.Number;
                voyage.VoyageId = voyages.VoyageId;
                foreach (var itenarary in voyages.Itineraries)
                {
                    var port = portData.Items.FirstOrDefault(item => item.PortId == itenarary.PortId);
                    if (port != null && !itenarary.IsSeaDay)
                    {
                        itenarary.PortName = port.Name;
                        voyage.Itineraries.Add(itenarary);
                    }
                }

                voyageResult.Add(voyage);
            }

            return voyageResult;
        }
Beispiel #47
0
 /// <summary>
 /// Отображение рейса текущего поезда для дальнейшего редактирования
 /// </summary>
 /// <param name="window"></param>
 private void EditVoyage(TrainInfoWindow window)
 {
     if (_trainToEdit == null || String.IsNullOrEmpty(TrainNum)) return;
     var voyage = VoyageBuilder.GetVoyageOfTrain(_trainToEdit.Id);
     if (voyage == null)
     {
         var newVoyage = new Voyage();
         newVoyage.DepartureDateTime = DateTime.Now;
         newVoyage.TrainId = _trainToEdit.Id;
         ContextKeeper.Voyages.Add(newVoyage);         
     }
     var voyageEditWin = new VoyageEditWindow();
     voyageEditWin.Show();
     Messenger.Default.Send(new TrainOfVoyageMessage(_trainToEdit.Id));
     window.Close();
 }
Beispiel #48
0
        private void SetVoyageInfo(int trainId)
        {
            this._voyage = VoyageBuilder.GetVoyageOfTrain(trainId);
            this.TrainNum = "Номер поезда: " + ContextKeeper.Trains
                .Where(train => train.Id == trainId)
                .Select(train => train.TrainNum)
                .First();
            if (this._voyage.Periodicity == null)
            {
                this.Periodicity = "0";
            }
            else
            {
                this.Periodicity = (this._voyage.Periodicity - 1).ToString();
            }

            if (this.Periodicity == null) this.Periodicity = 0.ToString();
            this.DepartureDate = (DateTime)this._voyage.DepartureDateTime.Value.Date;
            this.DepartureOffset = this.DepartureDate;
            this.ArrivalOffset = this.DepartureDate;
            RefreshRoutesOfVoyage();
        }