Esempio n. 1
0
 public void NaoCadastraComNomeVazio()
 {
     Cargo cargo = new Cargo(12, "", 'I');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool cadastrar = cargoRep.AdicionarCargo(cargo);
     Assert.AreEqual(true, cadastrar);
 }
 private FuncionarioBuilder()
 {
     _usuario = UsuarioBuilder.DadoUmUsuario().Build();
     _departamento = DepartamentoBuilder.DadoUmDepartamento().Build();
     _cargo = CargoBuilder.DadoUmCargo().Build();
     _programa = ProgramaBuilder.DadoUmPrograma().Build();
 }
Esempio n. 3
0
 public Boolean cadastrarCargo(Cargo objCargo)
 {
     objCargo.Codigo = obtemNovoId();
     try
     {
         if (!temDuplicidade(objCargo, "Cadastrar"))
         {
             db = ServidorSingleton.obterServidor().OpenClient();
             db.Store(objCargo);
             db.Commit();
             return true;
         }
         else {
             return false;
         }
     }
     catch(Exception e)
     {
         throw new Exception("Erro cadastrando o cargo :" + e.Message);
     }
     finally {
         db.Close();
         db.Dispose();
     }
 }
Esempio n. 4
0
 public void NaoAlteraCargoPraAtivoComEleicaoAberta()
 {
     Cargo cargo = new Cargo(42, "Sindico", 'A');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool altera = cargoRep.AtivarCargo(1);
     Assert.AreEqual(false, altera);
 }
Esempio n. 5
0
    void OnTriggerEnter(Collider otherObject)
    {
        Debug.Log(string.Format("Ore collided with {0} at {1}", otherObject.name, Time.time));

        if (otherObject.name == "Player")
        {
            Cargo ore = new Cargo(Cargo.CargoType.Ore);

            //different OreTypes are worth different amounts
            switch (ActiveOreType)
            {
            case OreType.Green:
                ore.Quantity = 1;
                break;
            case OreType.Blue:
                ore.Quantity = 2;
                break;
            case OreType.Red:
                ore.Quantity = 3;
                break;
            case OreType.Yellow:
                ore.Quantity = 5;
                break;
            }

            otherObject.SendMessage("PickupCargo", ore);
            Destroy(gameObject);
        }
    }
Esempio n. 6
0
        public void toCargoRoutingDTO()
        {
            var origin = L.HONGKONG;
            var destination = L.LONGBEACH;
            var cargo = new Cargo(new TrackingId("XYZ"), new RouteSpecification(origin, destination, DateTime.Now));

            var itinerary = new Itinerary(
                Leg.DeriveLeg(SampleVoyages.pacific1, L.HONGKONG, L.TOKYO),
                Leg.DeriveLeg(SampleVoyages.pacific1, L.TOKYO, L.LONGBEACH)
                );

            cargo.AssignToRoute(itinerary);

            var dto = DTOAssembler.toDTO(cargo);

            Assert.AreEqual(2, dto.getLegs().Count());

            LegDTO legDTO = dto.getLegs().ElementAt(0);
            Assert.AreEqual("PAC1", legDTO.getVoyageNumber());
            Assert.AreEqual("CNHKG", legDTO.getFrom());
            Assert.AreEqual("JNTKO", legDTO.getTo());

            legDTO = dto.getLegs().ElementAt(1);
            Assert.AreEqual("PAC1", legDTO.getVoyageNumber());
            Assert.AreEqual("JNTKO", legDTO.getFrom());
            Assert.AreEqual("USLBG", legDTO.getTo());
        }
 public Funcionario(Usuario usuario, string nome, string telefone, Departamento departamento, Cargo cargo, List<Programa> programa)
     : base(usuario, nome, telefone, programa)
 {
     Departamento = departamento;
     Cargo = cargo;
     Validar();
 }
Esempio n. 8
0
 public void CargoTest()
 {
     Cargo cargo = new Cargo("Cargo", 'A');
     Assert.AreEqual("Cargo", cargo.Nome);
     Assert.AreEqual(0, cargo.IdCargo);
     Assert.AreEqual('A', cargo.Situacao);
 }
Esempio n. 9
0
 public void AlterarCargoParaAtivo()
 {
     Cargo cargo = new Cargo(8, "Rei da Galaxia", 'A');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool altera = cargoRep.AtivarCargo(6);
     Assert.AreEqual(true, altera);
 }
Esempio n. 10
0
 public void CargoTest()
 {
     Cargo cargo = new Cargo(23, "Cargo");
     Assert.AreEqual("Cargo", cargo.Nome);
     Assert.AreEqual(23, cargo.IdCargo);
     Assert.AreEqual('\0', cargo.Situacao);
 }
Esempio n. 11
0
 public void CadastrarCargo()
 {
     Cargo cargo = new Cargo(6, "Deputado", 'A');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool cadastro = cargoRep.AdicionarCargo(cargo);
     Assert.AreEqual(true, cadastro);
 }
Esempio n. 12
0
 public void AlterarCargoParaInativo()
 {
     Cargo cargo = new Cargo(7, "Rei do Mundo", 'A');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool altera = cargoRep.InativarCargo(6);
     Assert.AreEqual(true, altera);
 }
Esempio n. 13
0
        public void updateCargo()
        {
            TrackingId trackingId = trackingIdFactory.nextTrackingId();
            RouteSpecification routeSpecification = new RouteSpecification(L.HONGKONG,
                L.GOTHENBURG,
                DateTime.Parse("2009-10-15"));

            Cargo cargo = new Cargo(trackingId, routeSpecification);
            cargoRepository.store(cargo);

            HandlingEvent handlingEvent = handlingEventFactory.createHandlingEvent(DateTime.Parse("2009-10-01 14:30"),
                cargo.TrackingId,
                V.HONGKONG_TO_NEW_YORK.VoyageNumber,
                L.HONGKONG.UnLocode,
                HandlingActivityType.LOAD,
                new OperatorCode("ABCDE"));

            handlingEventRepository.store(handlingEvent);

            Assert.That(handlingEvent.Activity, Is.Not.EqualTo(cargo.MostRecentHandlingActivity));

            cargoUpdater.updateCargo(handlingEvent.SequenceNumber);

            Assert.That(handlingEvent.Activity, Is.EqualTo(cargo.MostRecentHandlingActivity));
            Assert.True(handlingEvent.Activity != cargo.MostRecentHandlingActivity);

            systemEvents.AssertWasCalled(se => se.notifyOfCargoUpdate(cargo));
        }
Esempio n. 14
0
        public void Store(Cargo cargo)
        {
            cargoCollection.Save(cargo);

            // Delete-orphan does not seem to work correctly when the parent is a component
            //Session.CreateSQLQuery("delete from Leg where cargo_id = null").ExecuteUpdate();
        }
Esempio n. 15
0
        internal static CargoRoutingDTO toDTO(Cargo cargo)
        {
            var itinerary = cargo.Itinerary;

            var legDTOList = new List<LegDTO>();
            if(itinerary != null)
            {
                var legs = itinerary.Legs;

                legDTOList = new List<LegDTO>(legs.Count());
                foreach(Leg leg in legs)
                {
                    var legDTO = new LegDTO(
                      leg.Voyage.VoyageNumber.Value,
                      leg.LoadLocation.UnLocode.Value,
                      leg.UnloadLocation.UnLocode.Value,
                      leg.LoadTime,
                      leg.UnloadTime);
                    legDTOList.Add(legDTO);
                }
            }

            return new CargoRoutingDTO(
              cargo.TrackingId.Value,
              cargo.RouteSpecification.Origin.UnLocode.Value,
              cargo.RouteSpecification.Destination.UnLocode.Value,
              cargo.RouteSpecification.ArrivalDeadline,
              cargo.RoutingStatus == RoutingStatus.MISROUTED,
              legDTOList
            );
        }
Esempio n. 16
0
 public void NaoCadastraComNomeNulo()
 {
     Cargo cargo = new Cargo(22, null, 'A');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool cadastrar = cargoRep.AdicionarCargo(cargo);
     Assert.AreEqual(true, cadastrar);
 }
Esempio n. 17
0
 public void DeletarCargo()
 {
     Cargo cargo = new Cargo(100, "Presidente", 'I');
     CargoRepositorio cargoRep = new CargoRepositorio();
     bool delete = cargoRep.DeletarCargo(5);
     Assert.AreEqual(true, delete);
 }
Esempio n. 18
0
        public virtual JsonResult Crear(Cargo entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    entidad.UsuarioCreacion = UsuarioActual.IdUsuario.ToString();
                    entidad.UsuarioModificacion = UsuarioActual.IdUsuario.ToString();
                    CargoBL.Instancia.Add(entidad);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
Esempio n. 19
0
        public void setUp()
        {
            reportSubmission = MockRepository.GenerateMock<ReportSubmission>();
            CargoRepository cargoRepository = new CargoRepositoryInMem();
            HandlingEventRepository handlingEventRepository = new HandlingEventRepositoryInMem();
            HandlingEventFactory handlingEventFactory = new HandlingEventFactory(cargoRepository,
                new VoyageRepositoryInMem(),
                new LocationRepositoryInMem());

            TrackingId trackingId = new TrackingId("ABC");
            RouteSpecification routeSpecification = new RouteSpecification(L.HONGKONG, L.ROTTERDAM, DateTime.Parse("2009-10-10"));
            Cargo cargo = new Cargo(trackingId, routeSpecification);
            cargoRepository.store(cargo);

            HandlingEvent handlingEvent = handlingEventFactory.createHandlingEvent(
                DateTime.Parse("2009-10-02"),
                trackingId,
                null,
                L.HONGKONG.UnLocode,
                HandlingActivityType.RECEIVE,
                new OperatorCode("ABCDE")
                );
            handlingEventRepository.store(handlingEvent);

            cargo.Handled(handlingEvent.Activity);

            reportPusher = new ReportPusher(reportSubmission, cargoRepository, handlingEventRepository);
            eventSequenceNumber = handlingEvent.SequenceNumber;
        }
Esempio n. 20
0
 public Funcionario(string _nome, double _salario, DateTime _dataAdmisao, Cargo _cargoFuncionario)
 {
     Nome = _nome;
     Salario = _salario;
     DataAdmissao = _dataAdmisao;
     CargoFuncionario = _cargoFuncionario;
 }
        public void testCalculatePossibleRoutes()
        {
            TrackingId trackingId = new TrackingId("ABC");
            RouteSpecification routeSpecification = new RouteSpecification(L.HONGKONG,
                L.HELSINKI,
                DateTime.Parse("2009-04-01"));
            Cargo cargo = new Cargo(trackingId, routeSpecification);

            var candidates = externalRoutingService.fetchRoutesForSpecification(routeSpecification);
            Assert.NotNull(candidates);

            foreach(Itinerary itinerary in candidates)
            {
                var legs = itinerary.Legs;
                Assert.NotNull(legs);
                Assert.True(legs.Any());

                // Cargo origin and start of first leg should match
                Assert.AreEqual(cargo.RouteSpecification.Origin, legs.ElementAt(0).LoadLocation);

                // Cargo final destination and last leg stop should match
                Location lastLegStop = legs.Last().UnloadLocation;
                Assert.AreEqual(cargo.RouteSpecification.Destination, lastLegStop);

                for(int i = 0; i < legs.Count() - 1; i++)
                {
                    // Assert that all legs are connected
                    Assert.AreEqual(legs.ElementAt(i).UnloadLocation, legs.ElementAt(i + 1).LoadLocation);
                }
            }
        }
Esempio n. 22
0
        public void TestCalculatePossibleRoutes()
        {
            var trackingId = new TrackingId("ABC");
            var routeSpecification = new RouteSpecification(SampleLocations.HONGKONG,
                                                                           SampleLocations.HELSINKI, DateTime.Now);
            var cargo = new Cargo(trackingId, routeSpecification);

            voyageRepositoryMock.Setup(v => v.Find(It.IsAny<VoyageNumber>())).Returns(SampleVoyages.CM002);

            IList<Itinerary> candidates = externalRoutingService.FetchRoutesForSpecification(routeSpecification);
            Assert.IsNotNull(candidates);

            foreach (Itinerary itinerary in candidates)
            {
                IList<Leg> legs = itinerary.Legs;
                Assert.IsNotNull(legs);
                Assert.IsFalse(legs.IsEmpty());

                // Cargo origin and start of first leg should match
                Assert.AreEqual(cargo.Origin, legs[0].LoadLocation);

                // Cargo final destination and last leg stop should match
                Location lastLegStop = legs[legs.Count - 1].UnloadLocation;
                Assert.AreEqual(cargo.RouteSpecification.Destination, lastLegStop);

                for (int i = 0; i < legs.Count - 1; i++)
                {
                    // Assert that all legs are connected
                    Assert.AreEqual(legs[i].UnloadLocation, legs[i + 1].LoadLocation);
                }
            }

            voyageRepositoryMock.Verify();
        }
Esempio n. 23
0
        public bool AdicionarCargo(Cargo cargo)
        {
            bool podeCadastrar = PodeCadastrar(cargo);
            bool verificarNome = VerificarNomeNuloOuVazio(cargo);
            if (podeCadastrar && !Eleicao.Iniciou)
            {
                if (verificarNome)
                {
                    string connectionString = ConfigurationManager.ConnectionStrings["URNA"].ConnectionString;
                    using (TransactionScope transacao = new TransactionScope())
                    using (IDbConnection connection = new SqlConnection(connectionString))
                    {
                        IDbCommand comando = connection.CreateCommand();
                        comando.CommandText =
                            "INSERT INTO Cargo (Nome, Situacao) values(@paramNome, @paramSituacao)";
                        comando.AddParameter("@paramNome", cargo.Nome);
                        comando.AddParameter("@paramSituacao", cargo.Situacao);
                        connection.Open();
                        comando.ExecuteNonQuery();
                        transacao.Complete();
                        connection.Close();
                    }
                }
                return true;

            }
            else
            {
                return false;
            }
        }
Esempio n. 24
0
    protected void btnSalvar_Click(object sender, EventArgs e)
    {
        var Cargo = new Cargo();
        try
        {
            if (txtId.Text != "")
            {
                Cargo.IDCargo = int.Parse(txtId.Text);
                Cargo.Get();
            }

            Cargo.Descricao = txtNome.Text;
            Cargo.ColunaEstrutura = ddlColunaEstrutura.SelectedValue;
            Cargo.IDCargoPai = int.Parse(ddlCargoPai.SelectedValue);
            Cargo.Ordem = int.Parse(txtOrdem.Text);
            Cargo.Save();
            GetCargo((int)Cargo.IDCargo);

            Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>alert('Registro salvo.')</script>");
        }
        catch (Exception err)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>alert('" + FormatError.FormatMessageForJAlert(err.Message) + "')</script>");
        }
    }
 public void ValidarTest()
 {
     CargoRepositorio repositorio = new CargoRepositorio();
     Cargo cargo = new Cargo("Cargo", 'A');
     Assert.IsFalse(repositorio.Validar(cargo));
     cargo.IdCargo = 1;
     Assert.IsTrue(repositorio.Validar(cargo));
 }
Esempio n. 26
0
 public void Add(Cargo.Cargo cargo)
 {
     if (_capacity < cargo.Size())
     {
         throw new CargoExceedesVesselCapacityException("Cargo size exceeds vessel's available capacity.");
     }
     _cargos.Add(cargo);
 }
Esempio n. 27
0
    public override void InitializeTile()
    {
        MeshRenderer = GetComponent<MeshRenderer>();
        IsWater = false;
        TileResources = new Cargo();

        MeshRenderer.sharedMaterial = CloudMaterial;
    }
 public HandlingEvent mostRecentHandling(Cargo cargo)
 {
     return sessionFactory.GetCurrentSession().
         CreateQuery("from HandlingEvent where Cargo = :cargo order by completionTime desc").
         SetParameter("cargo", cargo).
         SetMaxResults(1).
         UniqueResult<HandlingEvent>();
 }
Esempio n. 29
0
 public void BuscaPorCargo()
 {
     Exercicios exer = new Exercicios();
     Cargo gerente = new Cargo("Gerente", 550.5);
     var funcionarios = exer.BuscarPorCargo(gerente);
     Assert.AreEqual(funcionarios.Any(it => it.Nome=="Margarete Ricardo"),true);
     Assert.AreEqual(funcionarios.Count,1);
 }
Esempio n. 30
0
 private CargoDetails assembleFrom(Cargo cargo)
 {
     CargoDetails cargoDetails = new CargoDetails();
     cargoDetails.setTrackingId(cargo.TrackingId.Value);
     cargoDetails.setFinalDestination(cargo.RouteSpecification.Destination.Name);
     cargoDetails.setCurrentLocation(cargo.LastKnownLocation.Name);
     cargoDetails.setCurrentStatus(cargo.TransportStatus.ToString());
     return cargoDetails;
 }
Esempio n. 31
0
 public static CargoTravelInfo FromCargo(Cargo cargo) => new CargoTravelInfo(cargo);
Esempio n. 32
0
        public void Handle(ChangeDestinationCommand message)
        {
            Cargo cargo = _cargoRepository.Find(message.CargoId);

            cargo.SpecifyNewRoute(new UnLocode(message.NewDestination));
        }
Esempio n. 33
0
 public Funcionario(Cargo cargo, double salarioBase)
 {
     this.cargo  = cargo;
     SalarioBase = salarioBase;
 }
Esempio n. 34
0
    static void Main(string[] args)
    {
        var list = new List <Car>();

        var n = int.Parse(Console.ReadLine());

        for (int i = 0; i < n; i++)
        {
            Cargo  cargo  = new Cargo();
            Engine engine = new Engine();

            Tire tire1 = new Tire();
            Tire tire2 = new Tire();
            Tire tire3 = new Tire();
            Tire tire4 = new Tire();

            Car car = new Car();

            var command = Console.ReadLine();
            var charArr = " ".ToCharArray();
            var parts   = command.Split(charArr, StringSplitOptions.RemoveEmptyEntries).ToArray();

            var model = parts[0];
            car.Model = model;

            var engineSpeed = int.Parse(parts[1]);
            engine.Speed = engineSpeed;
            var enginePower = int.Parse(parts[2]);
            engine.Power = enginePower;

            car.Engine = engine;

            var cargoWeight = int.Parse(parts[3]);
            cargo.Weight = cargoWeight;
            var cargoType = parts[4];
            cargo.Type = cargoType;

            car.Cargo = cargo;

            car.Tires = new List <Tire>();

            var tire1Pressure = double.Parse(parts[5]);
            tire1.Pressure = tire1Pressure;
            var tire1Age = int.Parse(parts[6]);
            tire1.Age = tire1Age;
            car.Tires.Add(tire1);

            var tire2Pressure = double.Parse(parts[7]);
            tire2.Pressure = tire2Pressure;
            var tire2Age = int.Parse(parts[8]);
            tire2.Age = tire2Age;
            car.Tires.Add(tire2);


            var tire3Pressure = double.Parse(parts[9]);
            tire3.Pressure = tire3Pressure;
            var tire3Age = int.Parse(parts[10]);
            tire3.Age = tire1Age;
            car.Tires.Add(tire3);


            var tire4Pressure = double.Parse(parts[11]);
            tire4.Pressure = tire4Pressure;
            var tire4Age = int.Parse(parts[12]);
            tire4.Age = tire4Age;
            car.Tires.Add(tire4);

            list.Add(car);
        }

        var cargoTypeCheck = Console.ReadLine();

        if (cargoTypeCheck == "flamable")
        {
            foreach (var flamableCargoType in list.Where(x => x.Cargo.Type.Equals("flamable")))
            {
                if (flamableCargoType.Engine.Power > 250)
                {
                    Console.WriteLine(flamableCargoType.Model);
                }
            }
        }
        else
        {
            foreach (var fragileCargoType in list.Where(x => x.Cargo.Type.Equals("fragile")))
            {
                foreach (var item1 in fragileCargoType.Tires.Where(x => x.Pressure < 1).ToList())
                {
                    Console.WriteLine(fragileCargoType.Model);
                    break;
                }
            }
        }
    }
Esempio n. 35
0
        private Vehicle FindVehicleForRoute(List <Vehicle> listVehicles, double routeSize, Cargo routeCargo)
        {
            for (int i = 0; i < listVehicles.Count; i++)
            {
                if (listVehicles[i].GetCurrentTravel().DoesSupportRoute(routeSize, routeCargo))
                {
                    return(listVehicles[i]);
                }
            }

            return(null);
        }
Esempio n. 36
0
    static void Main(string[] args)
    {
        var carList = new List <Car>();

        int n = int.Parse(Console.ReadLine());

        for (int i = 0; i < n; i++)
        {
            var splitInput = Console.ReadLine()
                             .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            string model = splitInput[0];

            int engineSpeed = int.Parse(splitInput[1]);
            int enginePower = int.Parse(splitInput[2]);
            int cargoWeight = int.Parse(splitInput[3]);

            string cargoType = splitInput[4];

            double tireOnePressure  = double.Parse(splitInput[5]);
            int    tireOneAge       = int.Parse(splitInput[6]);
            double tireTwoPressure  = double.Parse(splitInput[7]);
            int    tireTwoAge       = int.Parse(splitInput[8]);
            double tireTreePressure = double.Parse(splitInput[9]);
            int    tireTreeAge      = int.Parse(splitInput[10]);
            double tireFourPressure = double.Parse(splitInput[11]);
            int    tireFourAge      = int.Parse(splitInput[12]);

            var engine = new Engine(engineSpeed, enginePower);
            var cargo  = new Cargo(cargoWeight, cargoType);
            var tires  = new Tires[4];
            tires[0] = new Tires(tireOnePressure, tireOneAge);
            tires[1] = new Tires(tireTwoPressure, tireTwoAge);
            tires[2] = new Tires(tireTreePressure, tireTreeAge);
            tires[3] = new Tires(tireFourPressure, tireFourAge);

            var car = new Car(model, engine, cargo, tires);

            carList.Add(car);
        }

        var orderedlistWithCards = new List <Car>();

        string command = Console.ReadLine();

        if (command == "fragile")
        {
            orderedlistWithCards = carList
                                   .Where(c => c.Cargo.Type == "fragile" && c.Tires.Any(t => t.Pressure < 1))
                                   .ToList();
        }
        if (command == "flamable")
        {
            orderedlistWithCards = carList
                                   .Where(c => c.Cargo.Type == "flamable" && c.Engine.Power > 250)
                                   .ToList();
        }

        foreach (var car in orderedlistWithCards)
        {
            Console.WriteLine(car.Model);
        }
    }
Esempio n. 37
0
 public void AlterarCargo(Cargo oCargo)
 {
     _RepositorieCargo.AlterarCargo(oCargo);
 }
Esempio n. 38
0
 public void CadastrarCargo(Cargo oCargo)
 {
     _RepositorieCargo.CadastrarCargo(oCargo);
 }
Esempio n. 39
0
 public Cargo Adicionar(Cargo entity)
 {
     return(_repository.Adicionar(entity));
 }
Esempio n. 40
0
        public void testCargoFromHongkongToStockholm()
        {
            //Test setup: A cargo should be shipped from Hongkong to Stockholm,
            //and it should arrive in no more than two weeks.
            Location origin          = SampleLocations.HONGKONG;
            Location destination     = SampleLocations.STOCKHOLM;
            DateTime arrivalDeadline = DateUtil.ToDate("2009-03-18");


            //  Use case 1: booking
            //A new cargo is booked, and the unique tracking id is assigned to the cargo.
            TrackingId trackingId = bookingService.BookNewCargo(
                origin.UnLocode, destination.UnLocode, arrivalDeadline);

            //      The tracking id can be used to lookup the cargo in the repository.
            //Important: The cargo, and thus the domain model, is responsible for determining
            //the status of the cargo, whether it is on the right track or not and so on.
            //This is core domain logic.

            //Tracking the cargo basically amounts to presenting information extracted from
            //the cargo aggregate in a suitable way.
            Cargo cargo = cargoRepository.Find(trackingId);

            Assert.IsNotNull(cargo);
            Assert.AreEqual(TransportStatus.NOT_RECEIVED, cargo.Delivery.TransportStatus);
            Assert.AreEqual(RoutingStatus.NOT_ROUTED, cargo.Delivery.RoutingStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(cargo.Delivery.EstimatedTimeOfArrival, Delivery.ETA_UNKOWN);
            Assert.IsNull(cargo.Delivery.NextExpectedActivity);


            //   Use case 2: routing
            //A number of possible routes for this cargo is requested and may be
            //presented to the customer in some way for him/her to choose from.
            //Selection could be affected by things like price and time of delivery,
            //but this test simply uses an arbitrary selection to mimic that process.

            //The cargo is then assigned to the selected route, described by an itinerary.
            IList <Itinerary> itineraries = bookingService.RequestPossibleRoutesForCargo(trackingId);
            Itinerary         itinerary   = SelectPreferedItinerary(itineraries);

            cargo.AssignToRoute(itinerary);

            Assert.AreEqual(TransportStatus.NOT_RECEIVED, cargo.Delivery.TransportStatus);
            Assert.AreEqual(RoutingStatus.ROUTED, cargo.Delivery.RoutingStatus);
            Assert.AreNotEqual(Delivery.ETA_UNKOWN, cargo.Delivery.EstimatedTimeOfArrival);
            Assert.AreEqual(new HandlingActivity(HandlingType.RECEIVE, SampleLocations.HONGKONG),
                            cargo.Delivery.NextExpectedActivity);


            //   Use case 3: handling

            //A handling event registration attempt will be formed from parsing
            //the data coming in as a handling report either via
            //the web service interface or as an uploaded CSV file.

            //The handling event factory tries to create a HandlingEvent from the attempt,
            //and if the factory decides that this is a plausible handling event, it is stored.
            //If the attempt is invalid, for example if no cargo exists for the specfied tracking id,
            //the attempt is rejected.

            //Handling begins: cargo is received in Hongkong.
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-01"), trackingId, null, SampleLocations.HONGKONG.UnLocode,
                HandlingType.RECEIVE);

            Assert.AreEqual(TransportStatus.IN_PORT, cargo.Delivery.TransportStatus);
            Assert.AreEqual(SampleLocations.HONGKONG, cargo.Delivery.LastKnownLocation);

            // Next event: Load onto voyage CM003 in Hongkong
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-03"), trackingId, SampleVoyages.v100.VoyageNumber,
                SampleLocations.HONGKONG.UnLocode, HandlingType.LOAD);

            // Check current state - should be ok
            Assert.AreEqual(SampleVoyages.v100, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.HONGKONG, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.ONBOARD_CARRIER, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(
                new HandlingActivity(HandlingType.UNLOAD, SampleLocations.NEWYORK, SampleVoyages.v100),
                cargo.Delivery.NextExpectedActivity);

            //Here's an attempt to register a handling event that's not valid
            //because there is no voyage with the specified voyage number,
            //and there's no location with the specified UN Locode either.

            //This attempt will be rejected and will not affect the cargo delivery in any way.
            VoyageNumber noSuchVoyageNumber = new VoyageNumber("XX000");
            UnLocode     noSuchUnLocode     = new UnLocode("ZZZZZ");

            try
            {
                handlingEventService.RegisterHandlingEvent(
                    DateUtil.ToDate("2009-03-05"), trackingId, noSuchVoyageNumber, noSuchUnLocode,
                    HandlingType.LOAD);
                Assert.Fail("Should not be able to register a handling event with invalid location and voyage");
            }
            catch (CannotCreateHandlingEventException)
            {
            }


            // Cargo is now (incorrectly) unloaded in Tokyo
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-05"), trackingId, SampleVoyages.v100.VoyageNumber,
                SampleLocations.TOKYO.UnLocode, HandlingType.UNLOAD);

            // Check current state - cargo is misdirected!
            Assert.AreEqual(Voyage.NONE, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.TOKYO, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.IN_PORT, cargo.Delivery.TransportStatus);
            Assert.IsTrue(cargo.Delivery.IsMisdirected);
            Assert.IsNull(cargo.Delivery.NextExpectedActivity);


            // -- Cargo needs to be rerouted --
            // TODO cleaner reroute from "earliest location from where the new route originates"

            // Specify a new route, this time from Tokyo (where it was incorrectly unloaded) to Stockholm
            RouteSpecification fromTokyo = new RouteSpecification(SampleLocations.TOKYO, SampleLocations.STOCKHOLM,
                                                                  arrivalDeadline);

            cargo.SpecifyNewRoute(fromTokyo);

            // The old itinerary does not satisfy the new specification
            Assert.AreEqual(RoutingStatus.MISROUTED, cargo.Delivery.RoutingStatus);
            Assert.IsNull(cargo.Delivery.NextExpectedActivity);

            // Repeat procedure of selecting one out of a number of possible routes satisfying the route spec
            IList <Itinerary> newItineraries = bookingService.RequestPossibleRoutesForCargo(cargo.TrackingId);
            Itinerary         newItinerary   = SelectPreferedItinerary(newItineraries);

            cargo.AssignToRoute(newItinerary);

            // New itinerary should satisfy new route
            Assert.AreEqual(RoutingStatus.ROUTED, cargo.Delivery.RoutingStatus);

            // TODO we can't handle the face that after a reroute, the cargo isn't misdirected anymore
            //Assert.IsFalse(cargo.isMisdirected());
            //Assert.AreEqual(new HandlingActivity(LOAD, TOKYO), cargo.nextExpectedActivity());


            // -- Cargo has been rerouted, shipping continues --


            // Load in Tokyo
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-08"), trackingId, SampleVoyages.v300.VoyageNumber,
                SampleLocations.TOKYO.UnLocode, HandlingType.LOAD);

            // Check current state - should be ok
            Assert.AreEqual(SampleVoyages.v300, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.TOKYO, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.ONBOARD_CARRIER, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(
                new HandlingActivity(HandlingType.UNLOAD, SampleLocations.HAMBURG, SampleVoyages.v300),
                cargo.Delivery.NextExpectedActivity);

            // Unload in Hamburg
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-12"), trackingId, SampleVoyages.v300.VoyageNumber,
                SampleLocations.HAMBURG.UnLocode, HandlingType.UNLOAD);

            // Check current state - should be ok
            Assert.AreEqual(Voyage.NONE, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.HAMBURG, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.IN_PORT, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(
                new HandlingActivity(HandlingType.LOAD, SampleLocations.HAMBURG, SampleVoyages.v400),
                cargo.Delivery.NextExpectedActivity);


            // Load in Hamburg
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-14"), trackingId, SampleVoyages.v400.VoyageNumber,
                SampleLocations.HAMBURG.UnLocode, HandlingType.LOAD);

            // Check current state - should be ok
            Assert.AreEqual(SampleVoyages.v400, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.HAMBURG, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.ONBOARD_CARRIER, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(
                new HandlingActivity(HandlingType.UNLOAD, SampleLocations.STOCKHOLM, SampleVoyages.v400),
                cargo.Delivery.NextExpectedActivity);


            // Unload in Stockholm
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-15"), trackingId, SampleVoyages.v400.VoyageNumber,
                SampleLocations.STOCKHOLM.UnLocode, HandlingType.UNLOAD);

            // Check current state - should be ok
            Assert.AreEqual(Voyage.NONE, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.STOCKHOLM, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.IN_PORT, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.AreEqual(new HandlingActivity(HandlingType.CLAIM, SampleLocations.STOCKHOLM),
                            cargo.Delivery.NextExpectedActivity);

            // Finally, cargo is claimed in Stockholm. This ends the cargo lifecycle from our perspective.
            handlingEventService.RegisterHandlingEvent(
                DateUtil.ToDate("2009-03-16"), trackingId, null, SampleLocations.STOCKHOLM.UnLocode,
                HandlingType.CLAIM);

            // Check current state - should be ok
            Assert.AreEqual(Voyage.NONE, cargo.Delivery.CurrentVoyage);
            Assert.AreEqual(SampleLocations.STOCKHOLM, cargo.Delivery.LastKnownLocation);
            Assert.AreEqual(TransportStatus.CLAIMED, cargo.Delivery.TransportStatus);
            Assert.IsFalse(cargo.Delivery.IsMisdirected);
            Assert.IsNull(cargo.Delivery.NextExpectedActivity);
        }
Esempio n. 41
0
 public void CargoHasArrived(Cargo cargo)
 {
     System.Console.WriteLine("EVENT: cargo has arrived: " + cargo.TrackingId.IdString);
 }
Esempio n. 42
0
 public void Atualizar(Cargo entity)
 {
     _repository.Atualizar(entity);
 }
Esempio n. 43
0
 public void Remover(Cargo entity)
 {
     _repository.Remover(entity);
 }
Esempio n. 44
0
        private bool _handleMissionAcceptedEvent(MissionAcceptedEvent @event)
        {
            bool    update  = false;
            Haulage haulage = new Haulage();

            // Protect against duplicates & empty strings
            haulage = GetHaulageWithMissionId(@event.missionid ?? 0);
            if (haulage == null && !string.IsNullOrEmpty(@event.name))
            {
                Cargo cargo = new Cargo();

                string type = @event.name.Split('_').ElementAt(1)?.ToLowerInvariant();
                if (type != null && CHAINED.TryGetValue(type, out string value))
                {
                    type = value;
                }
                else if (type == "ds" || type == "rs" || type == "welcome")
                {
                    type = @event.name.Split('_').ElementAt(2)?.ToLowerInvariant();
                }

                switch (type)
                {
                case "altruism":
                case "collect":
                case "collectwing":
                case "delivery":
                case "deliverywing":
                case "mining":
                case "piracy":
                case "rescue":
                case "salvage":
                case "smuggle":
                {
                    bool   naval        = @event.name.ToLowerInvariant().Contains("rank");
                    string originSystem = EDDI.Instance?.CurrentStarSystem?.systemname;
                    haulage = new Haulage(@event.missionid ?? 0, @event.name, originSystem, @event.amount ?? 0, @event.expiry)
                    {
                        startmarketid = (type.Contains("delivery") && !naval) ? EDDI.Instance?.CurrentStation?.marketId ?? 0 : 0,
                        endmarketid   = (type.Contains("collect")) ? EDDI.Instance?.CurrentStation?.marketId ?? 0 : 0,
                    };

                    if (type.Contains("delivery") || type == "smuggle")
                    {
                        haulage.sourcesystem = EDDI.Instance?.CurrentStarSystem?.systemname;
                        haulage.sourcebody   = EDDI.Instance?.CurrentStation?.name;
                    }
                    else if (type == "rescue" || type == "salvage")
                    {
                        haulage.sourcesystem = @event.destinationsystem;
                    }

                    cargo = GetCargoWithEDName(@event.commodityDefinition?.edname);
                    if (cargo == null)
                    {
                        cargo = new Cargo(@event.commodityDefinition?.edname, 0);
                        AddCargo(cargo);
                    }
                    cargo.haulageData.Add(haulage);
                    cargo.CalculateNeed();
                    update = true;
                }
                break;
                }
            }
            return(update);
        }
Esempio n. 45
0
        public Car Create(string model, Engine engine, Cargo cargo, Tire[] tires)
        {
            Car car = new Car(model, engine, cargo, tires);

            return(car);
        }
Esempio n. 46
0
 public void ExcluirCargo(Cargo oCargo)
 {
     _RepositorieCargo.ExcluirCargo(oCargo);
 }
Esempio n. 47
0
 public DatosEmpleado(string _nombre, string _apellido, DateTime _fechanac, string _estadocivil, string _genero, DateTime _fechaingreso, Cargo _cargo)
 {
     this.nombre       = _nombre;
     this.apellido     = _apellido;
     this.fechanac     = _fechanac;
     this.estadocivil  = _estadocivil;
     this.genero       = _genero;
     this.fechaingreso = _fechaingreso;
     this.cargo        = _cargo;
 }
Esempio n. 48
0
        static void Main(string[] args)
        {
            int        n      = int.Parse(Console.ReadLine());
            List <Car> dbCars = new List <Car>();

            for (int i = 0; i < n; i++)
            {
                try
                {
                    string[] input       = Console.ReadLine().Split(' ');
                    string   model       = input[0];
                    int      engineSpeed = int.Parse(input[1]);
                    int      enginePower = int.Parse(input[2]);
                    int      cargoWeight = int.Parse(input[3]);
                    string   cargoType   = input[4];
                    double   tire1p      = double.Parse(input[5]);
                    double   tire1a      = double.Parse(input[6]);
                    double   tire2p      = double.Parse(input[7]);
                    double   tire2a      = double.Parse(input[8]);
                    double   tire3p      = double.Parse(input[9]);
                    double   tire3a      = double.Parse(input[10]);
                    double   tire4p      = double.Parse(input[11]);
                    double   tire4a      = double.Parse(input[12]);

                    Engine currentEngine = new Engine(engineSpeed, enginePower);
                    Cargo  currentCargo  = new Cargo(cargoWeight, cargoType);
                    Tire   currentTires  = new Tire(tire1p, tire1a, tire2p, tire2a, tire3p, tire3a, tire4p, tire4a);
                    Car    currentCar    = new Car(model, currentEngine, currentCargo, currentTires);

                    dbCars.Add(currentCar);
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            string command = Console.ReadLine();

            if (command == "fragile")
            {
                foreach (var entry in dbCars)
                {
                    bool tirePressureUnder1 = entry.Tires.PressureUnder1Percent();

                    if (entry.Cargo.Type == "fragile" && tirePressureUnder1 == true)
                    {
                        Console.WriteLine(entry.Model.ToString());
                    }
                }
            }
            else if (command == "flammable")
            {
                foreach (var entry in dbCars)
                {
                    if (entry.Engine.EnginePower > 250)
                    {
                        Console.WriteLine(entry.Model.ToString());
                    }
                }
            }
        }
Esempio n. 49
0
        public List <Route> CreateRoutes(Position startPosition, List <Vehicle> listFleetVehicles, List <Package> listPackages)
        {
            CreateVehicleTravels(listFleetVehicles);

            List <Economy> listEconomies = CreateListEconomies(startPosition, listPackages);
            List <Route>   listRoutes    = InitializeRoutes(startPosition, listPackages, listFleetVehicles);

            // Itera a lista de economias
            for (int i = 0; i < listEconomies.Count; i++)
            {
                var economy = listEconomies[i];

                // Verifica se o package A existe dentro da lista de rotas em uma das extremidades
                Route routeA = FindPackageOnRouteEdges(listRoutes, economy.packageAId);
                if (routeA == null)
                {
                    continue;
                }

                // Verifica se o packagee B existe dentro da lista de rotas em uma das extremidades
                Route routeB = FindPackageOnRouteEdges(listRoutes, economy.packageBId);
                if (routeB == null)
                {
                    continue;
                }

                // Verifica se o package A e o packagee B já estão na mesma rota
                // e se ambos estão nas extremidades, caso sim, vai para a próxima iteração
                if (routeA.Id == routeB.Id)
                {
                    continue;
                }

                //Ambos os packagees encontrados, pega o totalDistance e o totalDemmand
                double newRouteSize  = routeA.Size + routeB.Size - economy.value;
                Cargo  newRouteCargo = routeA.Cargo + routeB.Cargo;

                //Procura menor veiculo que comporta a rota combinada, caso nenhum seja encontrado, pula para a próxima economia
                Vehicle vehicle = FindVehicleForRoute(listFleetVehicles, newRouteSize, newRouteCargo);

                // Todos os veiculos sobrecarregados para o dia de hoje, avança para próximo dia
                // - Salvar a economia da rota (soma da economia dos clientes)
                // - Quando sobrecarregar veiculos por distancia percorrida:
                //      Pega as rotas sem veiculo alocado e passa para o segundo dia;
                //      Executa CreateRoutes para a lista de clientes do segundo dia;

                if (vehicle != null)
                {
                    // Remove todos os veiculos alocados para as duas rotas
                    routeA.RemoveAssignedVehicle();
                    routeB.RemoveAssignedVehicle();

                    // Verifica a posição em que os pacotes estão na rota
                    RouteEdge packageAEdge = CheckPackagePosition(routeA, economy.packageAId);
                    RouteEdge packageBEdge = CheckPackagePosition(routeB, economy.packageBId);

                    // Se package A está na esquerda e packagee B também, inverte B e adiciona em A
                    if (packageAEdge == RouteEdge.LEFT && packageBEdge == RouteEdge.LEFT)
                    {
                        MergeRoutes(listRoutes, routeA, routeB, vehicle, true);
                    }
                    // Se package A está na esquerda e packagee B a direita, adiciona em A
                    else if (packageAEdge == RouteEdge.LEFT && packageBEdge == RouteEdge.RIGHT)
                    {
                        MergeRoutes(listRoutes, routeA, routeB, vehicle, false);
                    }
                    // Se package A está na direita e packagee B a esquerda, adiciona em B
                    else if (packageAEdge == RouteEdge.RIGHT && packageBEdge == RouteEdge.LEFT)
                    {
                        MergeRoutes(listRoutes, routeB, routeA, vehicle, false);
                    }
                    // Se package A está na direita e packagee B também, inverte A e adiciona em B
                    else if (packageAEdge == RouteEdge.RIGHT && packageBEdge == RouteEdge.RIGHT)
                    {
                        MergeRoutes(listRoutes, routeB, routeA, vehicle, true);
                    }
                }
            }

            return(listRoutes);
        }
 public bool CalculoSeAplicaAoCargo(Cargo cargo)
 {
     return(Cargos.Contains(cargo));
 }
Esempio n. 51
0
 public RenderCargo(Actor self)
 {
     cargo  = self.Trait <Cargo>();
     facing = self.TraitOrDefault <IFacing>();
 }
Esempio n. 52
0
        private Cargo GetModel(int id)
        {
            Cargo result = DataBase.Cargos.Get(p => p.IdCargo == id).SingleOrDefault();

            return(result);
        }
 public Funcionario(string Nome, double Salario, Cargo Cargo)
 {
     this.Nome    = Nome;
     this.Salario = Salario;
     this.Cargo   = Cargo;
 }
Esempio n. 54
0
 public DeliveryViaTrainForm(Cargo cargo, TransportInformation transport, double totalPrice)
 {
     _cargo      = cargo;
     _transport  = transport;
     _totalPrice = totalPrice;
 }
Esempio n. 55
0
        static void Main(string[] args)
        {
            Console.WriteLine("Создаём порт Новороссийск");
            var novorossiysk = new Model.Port("Новороссийск", 1000);

            Console.WriteLine("Создаём порт Усть-Луга");
            var ustluga = new Model.Port("Усть-Луга", 2000);

            Console.WriteLine("Создаём дизельное топливо");
            var diesel = new Fuel(50);

            Console.WriteLine("Создаём грузы");
            var cargo1 = new Cargo(100000);
            var cargo2 = new Cargo(120000);
            var cargo3 = new Cargo(350000);
            var cargo4 = new Cargo(160000);
            var cargo5 = new Cargo(140000);
            var cargo6 = new Cargo(170000);
            var cargo7 = new Cargo(150000);
            var cargo8 = new Cargo(150000);

            Console.WriteLine("Создаём корабль Труженник");
            var worker = new Ship("Труженник", novorossiysk);

            Console.WriteLine("Заправляем Труженника");
            worker.Fill(diesel);
            Console.WriteLine("Загружаем Труженника");
            worker.Load(cargo1);
            worker.Load(cargo2);
            worker.Load(cargo3);
            worker.Load(cargo4);
            Console.WriteLine("Создаём маршрут для Труженника");
            var routeForWorker = new Route(ustluga);

            worker.SetRoute(routeForWorker);
            Console.WriteLine("Отправляем Труженника по маршруту");
            try
            {
                worker.Send();
                Console.WriteLine("Проверяем какие корабли находятся в порту Усть-Луга");
                foreach (var s in ustluga.InPort)
                {
                    Console.WriteLine(s.Title);
                }
                Console.WriteLine("Выводим стоимости маршрутов корабля Труженник");
                foreach (var r in worker.Routes)
                {
                    Console.WriteLine($"{r.Departure.Title}-{r.Arrival.Title} стоимость {r.Costs}");
                    Console.WriteLine($"Стоимость грузов {r.Sums}");
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Создаём корабль Большой");
            var big = new Ship("Большой", ustluga);

            /*Console.WriteLine("Заправляем Большого");
             * big.Fill(diesel);*/
            Console.WriteLine("Загружаем Большого");
            big.Load(cargo5);
            big.Load(cargo6);
            big.Load(cargo7);
            big.Load(cargo8);
            Console.WriteLine("Создаём маршрут для Большого");
            var routeForBig = new Route(novorossiysk);

            big.SetRoute(routeForBig);
            Console.WriteLine("Отправляем Большого по маршруту");
            try
            {
                big.Send();
                Console.WriteLine("Проверяем какие корабли находятся в порту Новороссийск");
                foreach (var s in novorossiysk.InPort)
                {
                    Console.WriteLine(s.Title);
                }
                Console.WriteLine("Выводим стоимости маршрутов корабля Большой");
                foreach (var r in big.Routes)
                {
                    Console.WriteLine($"{r.Departure.Title}-{r.Arrival.Title} стоимость {r.Costs}");
                    Console.WriteLine($"Стоимость грузов {r.Sums}");
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.Message);
            }

            XmlSerializer formatter = new XmlSerializer(typeof(Fuel));

            using (FileStream fs = new FileStream("fuel.xml", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, diesel);

                Console.WriteLine("Объект сериализован");
            }

            using (FileStream fs = new FileStream("fuel.xml", FileMode.OpenOrCreate))
            {
                Fuel newDiesel = (Fuel)formatter.Deserialize(fs);

                Console.WriteLine("Объект десериализован");
                Console.WriteLine("Цена: {0}", newDiesel.Cost);
            }

            BinaryFormatter bformatter = new BinaryFormatter();

            using (FileStream fs = new FileStream("ship.dat", FileMode.OpenOrCreate))
            {
                bformatter.Serialize(fs, worker);

                Console.WriteLine("Объект сериализован");
            }

            using (FileStream fs = new FileStream("ship.dat", FileMode.OpenOrCreate))
            {
                Ship newWorker = (Ship)bformatter.Deserialize(fs);

                Console.WriteLine("Объект десериализован");
                Console.WriteLine("Название корабля: {0}, порт: {1}", newWorker.Title, newWorker.Port.Title);
            }
        }
Esempio n. 56
0
        private void _handleCargoEvent(CargoEvent @event)
        {
            if (@event.vessel == Constants.VEHICLE_SHIP)
            {
                cargoCarried = @event.cargocarried;
                if (@event.inventory != null)
                {
                    List <CargoInfo> infoList = @event.inventory.ToList();

                    // Remove strays from the manifest
                    foreach (Cargo inventoryCargo in inventory.ToList())
                    {
                        string    name = inventoryCargo.edname;
                        CargoInfo info = @event.inventory.FirstOrDefault(i => i.name.Equals(name, StringComparison.OrdinalIgnoreCase));
                        if (info == null)
                        {
                            if (inventoryCargo.haulageData?.Any() ?? false)
                            {
                                // Keep cargo entry in manifest with zeroed amounts, if missions are pending
                                inventoryCargo.total   = 0;
                                inventoryCargo.haulage = 0;
                                inventoryCargo.owned   = 0;
                                inventoryCargo.stolen  = 0;
                                inventoryCargo.CalculateNeed();
                            }
                            else
                            {
                                // Strip out the stray from the manifest
                                _RemoveCargoWithEDName(inventoryCargo.edname);
                            }
                        }
                    }

                    // Update existing cargo in the manifest
                    while (infoList.Count() > 0)
                    {
                        string           name      = infoList.ToList().First().name;
                        List <CargoInfo> cargoInfo = infoList.Where(i => i.name.Equals(name, StringComparison.OrdinalIgnoreCase)).ToList();
                        Cargo            cargo     = inventory.FirstOrDefault(c => c.edname.Equals(name, StringComparison.OrdinalIgnoreCase));
                        if (cargo != null)
                        {
                            int total        = cargoInfo.Sum(i => i.count);
                            int stolen       = cargoInfo.Where(i => i.missionid == null).Sum(i => i.stolen);
                            int missionCount = cargoInfo.Where(i => i.missionid != null).Count();
                            if (total != cargo.total || stolen != cargo.stolen || missionCount != cargo.haulageData.Count())
                            {
                                UpdateCargoFromInfo(cargo, cargoInfo);
                                if (@event.update)
                                {
                                    return;
                                }
                            }
                        }
                        else
                        {
                            // Add cargo entries for those missing
                            cargo = new Cargo(name, 0);
                            UpdateCargoFromInfo(cargo, cargoInfo);
                            AddCargo(cargo);
                        }

                        infoList.RemoveAll(i => i.name == name);
                    }
                }
            }
        }
Esempio n. 57
0
        private void _handleCargoDepotEvent(CargoDepotEvent @event)
        {
            MissionMonitor missionMonitor  = (MissionMonitor)EDDI.Instance.ObtainMonitor("Mission monitor");
            Mission        mission         = missionMonitor?.GetMissionWithMissionId(@event.missionid ?? 0);
            Cargo          cargo           = new Cargo();
            Haulage        haulage         = new Haulage();
            int            amountRemaining = @event.totaltodeliver - @event.delivered;

            switch (@event.updatetype)
            {
            case "Collect":
            {
                cargo = GetCargoWithMissionId(@event.missionid ?? 0);
                if (cargo != null)
                {
                    // Cargo instantiated by either 'Mission accepted' event or previous 'WingUpdate' update
                    haulage           = cargo.haulageData.FirstOrDefault(ha => ha.missionid == @event.missionid);
                    haulage.remaining = amountRemaining;

                    // Update commodity definition if instantiated other than 'Mission accepted'
                    cargo.commodityDef   = @event.commodityDefinition;
                    haulage.originsystem = EDDI.Instance?.CurrentStarSystem?.systemname;
                }
                else
                {
                    // First exposure to new cargo.
                    cargo = new Cargo(@event.commodityDefinition.edname, 0);         // Total will be updated by following 'Cargo' event
                    AddCargo(cargo);

                    string originSystem = EDDI.Instance?.CurrentStarSystem?.systemname;
                    string name         = mission?.name ?? "MISSION_DeliveryWing";
                    haulage = new Haulage(@event.missionid ?? 0, name, originSystem, amountRemaining, null, true);
                    cargo.haulageData.Add(haulage);
                }
                haulage.collected     = @event.collected;
                haulage.delivered     = @event.delivered;
                haulage.startmarketid = @event.startmarketid;
                haulage.endmarketid   = @event.endmarketid;
            }
            break;

            case "Deliver":
            {
                cargo = GetCargoWithMissionId(@event.missionid ?? 0);
                if (cargo != null)
                {
                    // Cargo instantiated by either 'Mission accepted' event, previous 'WingUpdate' or 'Collect' updates
                    haulage = cargo.haulageData.FirstOrDefault(ha => ha.missionid == @event.missionid);
                    if (haulage != null)
                    {
                        haulage.remaining = amountRemaining;

                        //Update commodity definition
                        haulage.amount       = @event.totaltodeliver;
                        cargo.commodityDef   = @event.commodityDefinition;
                        haulage.originsystem = (@event.startmarketid == 0) ? EDDI.Instance?.CurrentStarSystem?.systemname : null;
                    }
                    else
                    {
                        string originSystem = (@event.startmarketid == 0) ? EDDI.Instance?.CurrentStarSystem?.systemname : null;
                        string name         = mission?.name ?? (@event.startmarketid == 0 ? "MISSION_CollectWing" : "MISSION_DeliveryWing");
                        haulage = new Haulage(@event.missionid ?? 0, name, originSystem, amountRemaining, null);
                        cargo.haulageData.Add(haulage);
                    }
                    cargo.CalculateNeed();
                }
                else
                {
                    // Check if cargo instantiated by previous 'Market buy' event
                    cargo = GetCargoWithEDName(@event.commodityDefinition.edname);
                    if (cargo == null)
                    {
                        cargo = new Cargo(@event.commodityDefinition.edname, 0);         // Total will be updated by following 'Cargo' event
                        AddCargo(cargo);
                    }
                    string originSystem = (@event.startmarketid == 0) ? EDDI.Instance?.CurrentStarSystem?.systemname : null;
                    string name         = mission?.name ?? (@event.startmarketid == 0 ? "MISSION_CollectWing" : "MISSION_DeliveryWing");
                    haulage = new Haulage(@event.missionid ?? 0, name, originSystem, amountRemaining, null, true);
                    cargo.haulageData.Add(haulage);
                    cargo.CalculateNeed();
                }
                haulage.collected   = @event.collected;
                haulage.delivered   = @event.delivered;
                haulage.endmarketid = (haulage.endmarketid == 0) ? @event.endmarketid : haulage.endmarketid;

                // Check for mission completion
                if (amountRemaining == 0)
                {
                    if (haulage.shared)
                    {
                        cargo.haulageData.Remove(haulage);
                        RemoveCargo(cargo);
                    }
                    else
                    {
                        haulage.status = "Complete";
                    }
                }
            }
            break;

            case "WingUpdate":
            {
                cargo = GetCargoWithMissionId(@event.missionid ?? 0);
                if (cargo != null)
                {
                    // Cargo instantiated by either 'Mission accepted' event, previous 'WingUpdate' or 'Collect' updates
                    haulage           = cargo.haulageData.FirstOrDefault(ha => ha.missionid == @event.missionid);
                    haulage.remaining = amountRemaining;
                }
                else
                {
                    // First exposure to new cargo, use 'Unknown' as placeholder
                    cargo = new Cargo("Unknown", 0);
                    AddCargo(cargo);
                    string name = mission?.name ?? (@event.startmarketid == 0 ? "MISSION_CollectWing" : "MISSION_DeliveryWing");
                    haulage = new Haulage(@event.missionid ?? 0, name, null, amountRemaining, null, true);
                    cargo.haulageData.Add(haulage);
                }
                cargo.CalculateNeed();

                int amount = Math.Max(@event.collected - haulage.collected, @event.delivered - haulage.delivered);
                if (amount > 0)
                {
                    string updatetype = @event.collected > haulage.collected ? "Collect" : "Deliver";
                    EDDI.Instance.enqueueEvent(new CargoWingUpdateEvent(DateTime.UtcNow, haulage.missionid, updatetype, cargo.commodityDef, amount, @event.collected, @event.delivered, @event.totaltodeliver));
                    haulage.collected     = @event.collected;
                    haulage.delivered     = @event.delivered;
                    haulage.startmarketid = @event.startmarketid;
                    haulage.endmarketid   = @event.endmarketid;
                }

                // Check for mission completion
                if (amountRemaining == 0)
                {
                    if (haulage.shared)
                    {
                        cargo.haulageData.Remove(haulage);
                        RemoveCargo(cargo);
                    }
                    else
                    {
                        haulage.status = "Complete";
                    }
                }
            }
            break;
            }
        }
Esempio n. 58
0
 /// <summary>
 ///     Initialise a job object
 /// </summary>
 public Job()
 {
     DeliveryTime          = new Time();
     RemainingDeliveryTime = new Frequency();
     CargoValues           = new Cargo();
 }
Esempio n. 59
0
 private CargoTravelInfo(Cargo cargo)
 {
     CargoId     = cargo.Id;
     Origin      = cargo.Origin?.Name;
     Destination = cargo.Destination?.Name;
 }
Esempio n. 60
0
 public void CargoWasMisdirected(Cargo cargo)
 {
     System.Console.WriteLine("EVENT: cargo was misdirected");
 }