示例#1
0
        public static Viaje buscarPorId(int id)
        {
            Viaje viaje = null;

            if (id > -1)
            {
                MySqlConnection con = conexionDB.ObtenerConexion();
                try
                {
                    string sql = "select ID, RECORRIDO, IDENTIFICADOR, DESDE, HASTA from VIAJES WHERE ID= " + id;
                    MySqlCommand cmd = new MySqlCommand(sql, con);
                    MySqlDataReader dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        viaje = new Viaje(dr.GetInt32(0), dr.GetInt32(1), dr.GetString(2), dr.GetString(3), dr.GetString(4), ViajeDiarioFacade.buscarPorViaje(id), HorarioFacade.buscarPorViaje(dr.GetInt32(0)));
                    }
                    dr.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Viaje buscarPorId: "+ex.Message);
                    viaje = null;
                }
                finally
                {
                    con.Close();
                }
            }
            return viaje;
        }
        public void Guardar()
        {
            int status = 0;

            if (teditor.Activo) status = 1;
            if (teditor.Inactivo) status = 0;

            if (teditor.ID < 0)//inserta
            {
                Viaje viaje = new Viaje
                {
                    FECHAVIAJE = teditor.Fecha
                ,
                    ESTATUS = status
                };
                data.Viajes.InsertOnSubmit(viaje);

            }
            else//modifica
            {
                var query = from viajes in data.Viajes
                            where viajes.CODIGO == teditor.ID
                            select viajes;
                Viaje viaje = query.First<Viaje>();
                viaje.ESTATUS = status;
                viaje.FECHAVIAJE = teditor.Fecha;
            }

            data.SubmitChanges();
            toDGV();
        }
 public compraForm(Viaje v)
 {
     InitializeComponent();
     viaje = v;
       //  btEncomienda.Visible = false;
     inicializar();
 }
 public ListadoButacas(Viaje viaje)
 {
     InitializeComponent();
     this.viaje = viaje;
     chkPasillo.Checked = true;
     chkVentanilla.Checked = true;
     txtPiso.Text = "1";
 }
        private void btn_generar_Click(object sender, EventArgs e)
        {
            Viaje viaje = new Viaje();
            viaje.Salida = salida;
            viaje.Llegada = DateTime.MinValue;
            viaje.Llegada_estimada = estimada;
            Aeronave seleccionado = new AeronaveDAO().FindById(Convert.ToInt32(dgv_aeronaves.CurrentRow.Cells[0].Value.ToString()));
            viaje.Aeronave = seleccionado;
            viaje.Ruta = ruta;
            viaje.Ruta_correcta = true;
            viaje.Cancelado = false;

            new ViajeDAO().Guardar(viaje);

            Main form = new Main();
            this.Close();
            form.Show();
        }
示例#6
0
 public bool RegistrarViaje(Viaje oViaje)
 {
     return(dao.RegistrerViaje(oViaje));
 }
示例#7
0
        public async Task Create(Viaje viaje)
        {
            await _terminalBusContext.Viajes.AddAsync(viaje);

            await _terminalBusContext.SaveChangesAsync();
        }
示例#8
0
 public void Update(Viaje viaje)
 {
     _repository.Update(viaje);
 }
示例#9
0
 /// <summary>
 /// Crea un nuevo elemento
 /// </summary>
 /// <param name="entity">Entidad con datos</param>
 public Viaje Create(Viaje entity)
 {
     entity.FechaAlta = DateTime.Now;
     return(_service.Create(entity));
 }
示例#10
0
 /// <summary>
 /// Actualiza un elemento existente
 /// </summary>
 /// <param name="entity">Entidad con datos</param>
 public void Update(Viaje entity)
 {
     entity.UltimaModificacion = DateTime.Now;
     _service.Update(entity);
 }
 // DELETE: api/Viajes/5
 public IHttpActionResult EliminarViaje(Viaje pViaje)
 {
     return(Json(new { Result = _lnViajes.EliminarViaje(pViaje.Id) }));
 }
 public IHttpActionResult InsertarViaje(Viaje pViaje)
 {
     return(Json(new { Result = _lnViajes.InsertarViaje(pViaje) }));
 }
示例#13
0
    protected void btnGrabar_Click(object sender, EventArgs e)
    {
        habilitar_panelRegistro(false);
        accion("Grabando..");
        Viaje h = new Viaje();

        if (validar())
        {
            if (txtCupo.Text != "")
            {
                h.cupo = Convert.ToInt32(txtCupo.Text);
            }
            else
            {
                h.cupo = -1;
            }

            h.descripcion = txtdescripcion.Text;

            if (txtPrecio.Text != "")
            {
                h.precio = Convert.ToInt32(txtPrecio.Text);
            }
            else
            {
                h.precio = -1;
            }

            h.destino = Convert.ToInt32(ddlDestino.SelectedValue);

            h.transporte = Convert.ToInt32(ddlTransporte.SelectedValue);

            h.hotel = Convert.ToInt32(ddlHotel.SelectedValue);

            if (rb_Disponibilidad.SelectedValue == "1")
            {
                h.disponible = true;
            }
            else
            {
                h.disponible = false;
            }

            if (txtFechaLlegada.Text != "")
            {
                h.fechaLlegada = Convert.ToDateTime(txtFechaLlegada.Text);
            }
            else
            {
                h.fechaLlegada = Convert.ToDateTime("01/01/2000");
            }

            if (txtFechaSalida.Text != "")
            {
                h.fechaSalida = Convert.ToDateTime(txtFechaSalida.Text);
            }
            else
            {
                h.fechaSalida = Convert.ToDateTime("01/01/2000");
            }

            if (txtimagen.Text != "")
            {
                h.imagen = txtimagen.Text;
            }

            if (!grabar)
            {
                h.id = Convert.ToInt32(txtId.Text);
            }


            GestorABMViaje.Grabar(h, grabar); //si está habilitado el textID es porq graba, sino actualiza
            cargarGrilla(chk_eliminados.Checked);
        }
    }
示例#14
0
 private void icono_cruz_Click(object sender, EventArgs e)
 {
     this.viaje = null;
     label_viaje.Text = "-";
     icono_cruz.Visible = false;
     b_guardar.Enabled = true;
     eliminarPasajes();
     eliminarEncomiendas();
 }
示例#15
0
        public async Task <ActionResult> Edit(Viaje viaje)
        {
            var response = await DAO_Api.PutAsync <Viaje>(_urlContorladorApi, viaje);

            return(RedirectToAction("Index"));
        }
        private void editar_Click(object sender, RoutedEventArgs e)
        {
            if (validarUpdate())
            {
                // UPDATE

                int contador = 0;
                foreach (UIElement ui in this.horarios.Children)
                {
                    int row = System.Windows.Controls.Grid.GetRow(ui);
                    int col = System.Windows.Controls.Grid.GetColumn(ui);

                    if ((row == 0) && (col == 0 || col == 1 || col == 2))
                    {
                        Label label = (Label)ui;
                    }
                    else
                    {
                        TextBox txt        = (TextBox)ui;
                        string  textoCelda = txt.Text;
                        if (row > 0 && col < 2)
                        {
                            if (contador == 0)
                            {
                                listHorariosLlegadaUpdate.Add(textoCelda);
                                contador = 1;
                            }
                            else
                            {
                                listHorariosSalidaUpdate.Add(textoCelda);
                                contador = 0;
                            }
                        }
                    }
                }


                MySqlConnection con;

                for (int i = 0; i < (paradas.Count); i++)
                {
                    con = conexionDB.ObtenerConexion();
                    Viaje ciudad = ViajeFacade.buscarPorId(this.id_viaje);

                    Parada paradaCiudad = ParadaFacade.buscarPorRecorridoCiudad(ciudad.recorrido, this.paradas[i]);

                    string       updateString  = "UPDATE HORARIOS SET LLEGADA=?llegada, SALIDA=?salida WHERE VIAJE=?viaje AND PARADA=?parada";
                    MySqlCommand updateCommand = new MySqlCommand(updateString, con);
                    updateCommand.Parameters.Add("?llegada", listHorariosLlegadaUpdate[i]);
                    updateCommand.Parameters.Add("?salida", listHorariosSalidaUpdate[i]);
                    updateCommand.Parameters.Add("?viaje", this.id_viaje);
                    updateCommand.Parameters.Add("?parada", paradaCiudad.id);

                    updateCommand.ExecuteNonQuery();
                    con.Close();
                }

                MySqlConnection con2 = conexionDB.ObtenerConexion();
                string          updateDatosViajes  = "UPDATE VIAJES_DIARIOS SET BUS=?bus, AUXILIAR=?auxiliar,CHOFER=?chofer WHERE VIAJE=?viaje";
                MySqlCommand    updateDatosCommand = new MySqlCommand(updateDatosViajes, con2);
                updateDatosCommand.Parameters.Add("?bus", comboBus.Text);
                updateDatosCommand.Parameters.Add("?auxiliar", obtenerRutPersonaByNombre(comboAuxiliar.Text, "AUXILIAR"));
                updateDatosCommand.Parameters.Add("?chofer", obtenerRutPersonaByNombre(comboChofer.Text, "CHOFER"));
                updateDatosCommand.Parameters.Add("?viaje", this.id_viaje);

                updateDatosCommand.ExecuteNonQuery();
                con2.Close();

                nuevoViajeDiario = new nuevoViaje();
                nuevoViajeDiario.Show();
                nuevoViajeDiario.saludo.Text     = "Gracias por actualizar nuestros registros";
                nuevoViajeDiario.textBlock1.Text = "Se ha actualizado correctamente el viaje en el sistema";
            }
        }
 public ViajeView createViajeViewFromViaje(Viaje viaje)
 {
     return(new ViajeView(viaje.Inicio, viaje.Fin, viaje.CantidadKilometros, viaje.Monto));
 }
        private void seleccionar(DataGridView dataGridView1)
        {
            Compra.inicializar();
            string idViaje = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string fechaSalida = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string precioPasaje = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string precioKg = dataGridView1[4, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string matriculaAeronave = dataGridView1[6, dataGridView1.CurrentCell.RowIndex].Value.ToString();

            Viaje elViaje = new Viaje(idViaje,fechaSalida,precioPasaje,precioKg,matriculaAeronave);
               // vdammy.matriculaAeronave = "BZD-177";
            elViaje.kgs_disponibles = dataGridView1[8, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            elViaje.butacas_disponibles = dataGridView1[7, dataGridView1.CurrentCell.RowIndex].Value.ToString();

             (new compraForm(elViaje)).Show();
             txtCityOrigen.Text = "";
             txtDestino.Text = "";
               //  dataGridView1.DataSource = null;
             dgvViaje.Visible = false;
            this.Hide();
        }
示例#19
0
        private void listado_de_viajes_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(this.viaje != null){
                MessageBox.Show("Ya existe un viaje seleccionado. Para seleccionar otro debe borrar la selección actual", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (e.ColumnIndex == 7)
            {
                Int32 id_viaje = Convert.ToInt32(listado_de_viajes.Rows[e.RowIndex].Cells["id_viaje"].Value.ToString());
                StringBuilder sb = new StringBuilder();
                sb.Append("select vi.ID_VIAJE, vi.ID_MICRO, re.ID_RECORRIDO, ts.DESCRIPCION, vi.F_SALIDA, vi.F_LLEGADA_ESTIMADA ");
                sb.Append("from SASHAILO.Viaje vi join SASHAILO.Recorrido re on re.ID_RECORRIDO=vi.ID_RECORRIDO ");
                sb.Append("join SASHAILO.Tipo_Servicio ts on ts.ID_TIPO_SERVICIO=re.ID_TIPO_SERVICIO ");
                sb.Append("where vi.ID_VIAJE = " + id_viaje);
                Conexion cn = new Conexion();
                SqlDataReader consulta = cn.consultar(sb.ToString());
                if (consulta.Read())
                {
                    int id_micro = consulta.GetInt32(1);
                    decimal id_recorrido = consulta.GetDecimal(2);
                    String ts = consulta.GetString(3);
                    DateTime f_salida = consulta.GetDateTime(4);
                    DateTime f_llegada_estim = consulta.GetDateTime(4);

                    Viaje vi = new Viaje();
                    vi.id_viaje = id_viaje;
                    vi.id_micro = id_micro;
                    vi.id_recorrido = id_recorrido;
                    vi.tipo_servicio = ts;
                    vi.f_salida = f_salida;
                    vi.f_llegada_estim = f_llegada_estim;

                    this.viaje = vi;
                    label_viaje.Text = this.viaje.ToString();
                    icono_cruz.Visible = true;
                    b_guardar.Enabled = false;

                }
                cn.desconectar();
            }
        }
示例#20
0
    public static List <Viaje> BuscarPorPais(int?id) //toma por parámetro un id de País, y devuelve una lista de Viajes de ese país
    {
        SqlConnection cn    = new SqlConnection(GestorHotel.CadenaConexion);
        Viaje         v     = null;
        List <Viaje>  lista = new List <Viaje>();

        try
        {
            cn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.Parameters.Clear();
            cmd.Connection = cn;
            string sql = "";
            if (id != null) //TODO 01 Refactorizar!
            {
                if (id == 0)
                {
                    sql = "select id, descripcion, imagen, precio, destino, transporte from Viaje";
                }
                else
                {
                    sql = "select v.id, v.descripcion, v.imagen, v.precio, v.destino, v.transporte "
                          + "from Viaje v "
                          + "join Destino d on v.destino=d.id "
                          + "where d.pais=@id";
                    cmd.Parameters.Add(new SqlParameter("@id", id));
                }
            }
            else
            {
                sql = "select id, descripcion, imagen, precio, destino, transporte from Viaje";
            }

            cmd.CommandText = sql;
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                v                     = new Viaje();
                v.id                  = (int)dr["id"];
                v.destino             = (int)dr["destino"];
                v.destino_descripcion = obtenerDescripcion("Destino", v.id);
                v.transporte          = (int)dr["transporte"];
                v.imagen              = (string)dr["imagen"];
                v.precio              = (int)dr["precio"];

                v.descripcion = ToString(v);
                lista.Add(v);
            }
            dr.Close();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (cn != null && cn.State == ConnectionState.Open)
            {
                cn.Close();
            }
        }
        return(lista);
    }
示例#21
0
 private void OnViajeReceived(Viaje viajeReceived)
 {
     Viaje = viajeReceived;
     //Distancia = viajeReceived.Distancia.DistanciaKM;
     RaisePropertyChanged("Viaje");
 }
示例#22
0
    public static Viaje buscarPorId(int id, bool eliminados)
    {
        // procedimiento almacenado

        SqlConnection cn = new SqlConnection(GestorHotel.CadenaConexion);
        Viaje         v  = null;

        try
        {
            cn.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = cn;
            cmd.Parameters.Clear();
            cmd.Connection = cn;
            string sql = "";
            if (eliminados)
            {
                sql = "select * from Viaje where id = @id AND eliminado=1";
            }
            else
            {
                sql = "select * from Viaje where id = @id AND (eliminado is NULL OR eliminado=0)";
            }
            cmd.CommandText = sql;
            cmd.Parameters.Add(new SqlParameter("@id", id));
            //cmd.Parameters.Add(new SqlParameter("@eliminado", 0));

            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                v    = new Viaje();
                v.id = (int)dr["id"];
                //h.descripcion = dr["descripcion"].ToString();
                v.imagen              = dr["imagen"].ToString();
                v.hotel               = (int)dr["hotel"];
                v.precio              = (int)dr["precio"];
                v.fechaSalida         = (DateTime)dr["fechaSalida"];
                v.fechaLlegada        = (DateTime)dr["fechaLlegada"];
                v.destino             = (int)dr["destino"];
                v.destino_descripcion = obtenerDescripcion("Destino", v.id);
                v.cupo        = (int)dr["cupo"];
                v.transporte  = (int)dr["transporte"];
                v.disponible  = (Boolean)dr["disponible"];
                v.descripcion = ToString(v);
            }
            dr.Close();
        }

        catch (Exception)
        {
            throw;
        }

        finally
        {
            if (cn != null && cn.State == ConnectionState.Open)
            {
                cn.Close();
            }
        }

        return(v);
    }
 // PUT: api/Viajes/5
 public IHttpActionResult ModificarViaje(Viaje pViaje)
 {
     return(Json(new { Result = _lnViajes.ModificarViaje(pViaje) }));
 }
示例#24
0
 public static string ToString(Viaje v)
 {
     return("Viajá a " + obtenerDescripcion("Destino", v.destino) + " el " + v.fechaSalida.ToString() + " en " + obtenerDescripcion("Transporte", v.transporte) + " a sólo " + v.precio.ToString());
 }
示例#25
0
 public void UpdateViaje(Viaje viaje)
 {
     throw new NotImplementedException();
 }
        private void HandleClientComm(object client)
        {
            TcpClient     tcpClient    = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            ASCIIEncoding encoder      = new ASCIIEncoding();

            byte[] buffer = encoder.GetBytes("Connected");
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();

            byte[] message = new byte[4096];
            int    bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    lock (this)
                    {
                        clientesConectados--;
                        txtConectados.Text = clientesConectados.ToString();
                    }
                    break;
                }

                //message has successfully been received
                encoder = new ASCIIEncoding();
                System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                lastMessage = encoder.GetString(message, 0, bytesRead);
                String[] solicitud = lastMessage.Split('/');
                // MessageBox.Show(solicitud[0], "Avión TCP", MessageBoxButtons.OK);
                string mensaje = "default";

                switch (solicitud[0])
                {
                //Caso en el que cliente solicita validar usuario y clave.
                case "ValidarUsuario":
                    Conductor conductorValidado = new Conductor();
                    Viaje     viajeEnCurso      = new Viaje();
                    conductorValidado = datos.ValidarUsuario(solicitud[1], solicitud[2]);
                    if (conductorValidado.Validado != null)
                    {
                        viajeEnCurso = datos.ObtenerViajesActivos(conductorValidado.Identificacion);
                    }
                    //MessageBox.Show("Resultado de Validacion:"+nuevoConductor.Validado, "Informacion", MessageBoxButtons.OK);
                    switch (conductorValidado.Validado)
                    {
                    case null:
                        mensaje = "noexiste";
                        break;

                    //Si se encuentra validado envia la informacion del usuario al cliente
                    case "validado":
                        if (viajeEnCurso.Estado != "en_curso")
                        {
                            mensaje = "validado" + "/" + conductorValidado.Identificacion + "/" + conductorValidado.Nombre + "/" + conductorValidado.PrimerApellido +
                                      "/" + conductorValidado.SegundoApellido;
                        }
                        else
                        {
                            mensaje = "validadoyencurso" + "/" + conductorValidado.Identificacion + "/" + conductorValidado.Nombre + "/" + conductorValidado.PrimerApellido +
                                      "/" + conductorValidado.SegundoApellido + "/" + viajeEnCurso.ViajeID + "/" + viajeEnCurso.LugarInicio + "/" + viajeEnCurso.LugarFinalizacion
                                      + "/" + viajeEnCurso.Carga + "/" + viajeEnCurso.TiempoEstimado + "/" + viajeEnCurso.UbicacionActual + "/" + viajeEnCurso.FechaCreacion;
                        }
                        break;

                    case "esperando":
                        mensaje = "esperando";
                        break;
                    }
                    buffer = encoder.GetBytes(mensaje);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    break;

                case "RegistrarUsuario":
                    //crea un objeto conductor para proceder al registro
                    Conductor nuevoConductor = new Conductor();
                    nuevoConductor.Identificacion  = solicitud[1];
                    nuevoConductor.Nombre          = solicitud[2];
                    nuevoConductor.PrimerApellido  = solicitud[3];
                    nuevoConductor.SegundoApellido = solicitud[4];
                    nuevoConductor.Usuario         = solicitud[5];
                    nuevoConductor.Contrasena      = solicitud[6];
                    //crea un objeto camion para proceder al registro
                    Camion nuevoCamion = new Camion();
                    nuevoCamion.Placa  = solicitud[7];
                    nuevoCamion.Marca  = solicitud[8];
                    nuevoCamion.Modelo = solicitud[9];

                    try
                    {
                        datos.AgregarConductor(nuevoConductor);
                        datos.AgregarCamion(nuevoCamion);
                        datos.AgregarConductorCamion(nuevoConductor.Identificacion, nuevoCamion.Placa);
                        //MessageBox.Show("Resultado de Validacion:"+nuevoConductor.Validado, "Informacion", MessageBoxButtons.OK);
                        mensaje = "registrado/Fin";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error al Intentar Registro en la base de datos" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        mensaje = "error/Fin";
                    }
                    buffer = encoder.GetBytes(mensaje);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    break;

                case "CrearViaje":
                    //crea un objeto conductor para proceder al registro
                    Viaje nuevoViaje = new Viaje();
                    nuevoViaje.Identificacion    = solicitud[1];
                    nuevoViaje.LugarInicio       = solicitud[2];
                    nuevoViaje.LugarFinalizacion = solicitud[3];
                    nuevoViaje.TiempoEstimado    = solicitud[5];
                    nuevoViaje.Carga             = solicitud[4];
                    nuevoViaje.FechaCreacion     = solicitud[6];
                    nuevoViaje.UbicacionActual   = solicitud[2];   //En nuevo viaje ubicacion actuar es el inicio

                    try
                    {
                        datos.AgregarViaje(nuevoViaje);
                        nuevoViaje = datos.ObtenerViajesActivos(solicitud[1]);
                        //MessageBox.Show("Resultado de Validacion:"+nuevoConductor.Validado, "Informacion", MessageBoxButtons.OK);
                        mensaje = nuevoViaje.ViajeID.ToString() + "/Fin";     //Retorna el ID creado para el viaje
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error al Intentar Registro en la base de datos" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        mensaje = "error/Fin";
                    }
                    buffer = encoder.GetBytes(mensaje);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    break;

                    //Caso en el que cliente solicita consultar las notas.
                    //    case "Volar":
                    //Llamado a Metodo YYY

                    /*buffer = encoder.GetBytes(mensaje);
                     * clientStream.Write(buffer, 0, buffer.Length);
                     * clientStream.Flush();
                     * MessageBox.Show("BOTON VOLAR--SERVIDRO", "Avión TCP", MessageBoxButtons.OK);
                     * break;
                     * case "ZZZ":
                     * try
                     * {
                     *  //Llamado a Metodo ZZZ
                     *  buffer = encoder.GetBytes(mensaje);
                     *  clientStream.Write(buffer, 0, buffer.Length);
                     *  clientStream.Flush();
                     *  break;
                     * }
                     * catch
                     * {
                     *  MessageBox.Show("Ocurrio error al registra Alumn...", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     *  break;
                     * }*/
                }
                lock (this)
                {
                    txtMensajesRecibidos.Text          += Environment.NewLine + lastMessage;
                    txtMensajesRecibidos.SelectionStart = txtMensajesRecibidos.Text.Length;
                    txtMensajesRecibidos.ScrollToCaret();
                    txtMensajesRecibidos.Refresh();
                }
            }
            tcpClient.Close();
            lock (this)
            {
                //clientesConectados--;
                txtConectados.Text = clientesConectados.ToString();
            }
        }
示例#27
0
 /// <summary>
 /// Elimina un elemento existente
 /// </summary>
 /// <param name="entity">Entidad con datos</param>
 public void Delete(Viaje entity)
 {
     _service.Delete(entity);
 }
示例#28
0
 public static void EditarViaje(Viaje Viaje, ApplicationDbContext _context)
 {
     _context.Entry(Viaje).State = EntityState.Modified;
     _context.SaveChanges();
 }
示例#29
0
 public void Create(Viaje viaje)
 {
     _repository.Insert(viaje);
 }
示例#30
0
 public ColectivoControls(Viaje viaje, List <Pasaje> pasajesReservados)
 {
     InitializeComponent();
     setearAsientosYreservados(viaje, pasajesReservados);
 }
示例#31
0
 public void SeleccionarChofer(Viaje viaje, PickUpRequest pickUp)
 {
     throw new NotImplementedException();
 }
示例#32
0
        public Confirmacion(List <String> detalle, List <int> pasajerosIds, List <int> butacasNumeros, List <int> clientesIds, List <decimal> pesos, Viaje v, Aeronave a, LoginForm loginform)
        {
            this.InitializeComponent();

            this.pasajerosIds     = pasajerosIds;
            this.butacasNumeros   = butacasNumeros;
            this.clientesIds      = clientesIds;
            this.pesos            = pesos;
            this.selectedAeronave = a;
            this.selectedViaje    = v;

            this.detalleTextbox.Lines = detalle.ToArray();
            this.fillCombos();

            if (loginform == null || loginform.loggedUser == null)
            {
                this.medioDePagoCombo.Enabled = false;
            }
        }
示例#33
0
 public static void GuardarViaje(Viaje Viaje, ApplicationDbContext _context)
 {
     //Viaje.Activo = true;
     _context.Viajes.Add(Viaje);
     _context.SaveChanges();
 }
示例#34
0
        public override async Task ReceiveAsync(string message)
        {
            var receiveMessage = JsonConvert.DeserializeObject <ReceiveMessage>(message);

            Debug.WriteLine("Received socket signal");
            var messageType = receiveMessage.Type;

            if (messageType == "chat")
            {
                Debug.WriteLine("New Message");
                var receivers = Handler.Connections.FindAll(m => ((ChatConnection)m).SocketId == receiveMessage.ReceiverId);

                if (receivers.Count != 0)
                {
                    receivers.ForEach(async delegate(WebSocketConnection receiver)
                    {
                        var sendMessage = JsonConvert.SerializeObject(new SendMessage
                        {
                            Sender  = SocketId,
                            Type    = "chat",
                            Message = receiveMessage.Message
                        });
                        var chatRecevier = (ChatConnection)receiver;
                        await chatRecevier.SendMessageAsync(sendMessage);
                    });
                }
                else
                {
                    var sendMessage = JsonConvert.SerializeObject(new SendMessage
                    {
                        Sender  = SocketId,
                        Type    = "SocketError",
                        Message = "Can not seed to " + receiveMessage.ReceiverId
                    });

                    await SendMessageAsync(sendMessage);
                }
            }
            else if (messageType == "gps")           // Socket module for GPS location update.
            {
                /*
                 * GPS location data will be read from socket data as Location1
                 * Location1 in socket data will be saved to VehiculoPosicion
                 */
                Debug.WriteLine("GPS update");
                if (receiveMessage.Location1 != null)
                {
                    try
                    {
                        //Debug.WriteLine("GPS update");
                        if (_context.VehiculoPosicion.Count <VehiculoPosicion>(s => s.IdCuentaUsuario == Int32.Parse(SocketId)) > 0)
                        {
                            Debug.WriteLine("GPS position Update");
                            var entity = _context.VehiculoPosicion.Where(s => s.IdCuentaUsuario == Int32.Parse(SocketId)).First <VehiculoPosicion>();
                            entity.Latitud             = receiveMessage.Location1.Latitud;
                            entity.Longitud            = receiveMessage.Location1.Longitud;
                            entity.UltimaActualizacion = DateTime.Now;
                            _context.Update <VehiculoPosicion>(entity);
                        }
                        else
                        {
                            //Debug.WriteLine("GPS position Add");
                            var entity = new VehiculoPosicion
                            {
                                IdCuentaUsuario     = Int32.Parse(SocketId),
                                Latitud             = receiveMessage.Location1.Latitud,
                                Longitud            = receiveMessage.Location1.Longitud,
                                UltimaActualizacion = DateTime.Now
                            };
                            //entity.UltimaActualizacion = DateTime.Now;
                            _context.VehiculoPosicion.Add(entity);
                        }

                        _context.SaveChanges();
                    } catch (Exception e)
                    {
                        Console.WriteLine("---------Exception--------");
                        Console.WriteLine(e.Message);
                        Console.WriteLine("-----Trace----");
                        Console.WriteLine(e.StackTrace);
                        Console.WriteLine("-----End----");
                    }
                }
            }
            else if (messageType == "new_trip")      // Socket module for New Trip Request
            {
                /*
                 * New socket request will be requested with socket data
                 * Location1: from place
                 * Location2: to place
                 * Status: should be 1 when new trip
                 */
                /* This new socket data will trigger new trip to drivers in 10km*/
                /* Making New Viaje data */
                Debug.WriteLine("New Trip Request");
                var userioEntity = _context.CuentasUsuario.Where(s => s.Id == Int32.Parse(SocketId)).First <CuentaUsuario>();
                if (userioEntity == null)
                {
                    Debug.WriteLine("User does not exist");
                    return;
                }
                var eStatusViajeEntity = _context.EstatusViajes.Where(s => s.Id == receiveMessage.Status).First <EstatusViaje>();
                var viajeEntity        = new Viaje
                {
                    LatitudOrigen      = receiveMessage.Location1.Latitud.ToString(),
                    LongitudOrigen     = receiveMessage.Location1.Longitud.ToString(),
                    LatitudDestino     = receiveMessage.Location2.Latitud.ToString(),
                    LongitudDestino    = receiveMessage.Location2.Longitud.ToString(),
                    EstatusViajeId     = receiveMessage.Status,
                    FechaAlta          = DateTime.Now,
                    UltimaModificacion = DateTime.Now,
                    EstatusViaje       = eStatusViajeEntity
                };
                _context.Viajes.Add(viajeEntity);
                _context.SaveChanges();
                Debug.WriteLine("viajeId: " + viajeEntity.Id.ToString());

                var viajesClienteEntity = new ViajeUsuario
                {
                    ClienteId = (int)userioEntity.Id,
                    ViajeId   = (int)viajeEntity.Id,
                    FechaAlta = DateTime.Now
                };
                _context.ViajesUsuarios.Add(viajesClienteEntity);
                _context.SaveChanges();
                Debug.WriteLine("viajeId: " + viajeEntity.Id.ToString() + "clienteId: " + viajesClienteEntity.Id.ToString());

                // Finding and Sending requests to drivers in 10km
                var activeUsuarioEntities = _context.CuentasUsuario.Where <CuentaUsuario>(s => s.EnServicio == true && s.IdTipoCuenta == 1);
                int requestedDriverCnt    = 0;
                foreach (var entity in activeUsuarioEntities)
                {
                    if (requestedDriverCnt == 10)
                    {
                        break;
                    }
                    var viajeConductor = _context.ViajesConductores.Where(s => s.IdConductor == entity.Id).Last <ViajeConductor>();
                    if (viajeConductor.Viaje.EstatusViajeId == 1)
                    {
                        var driverPositionEntity = _context.VehiculoPosicion.Where(s => s.IdCuentaUsuario == entity.Id).First <VehiculoPosicion>();

                        GeoCoordinate clientPosition = new GeoCoordinate(double.Parse(viajeEntity.LatitudOrigen), double.Parse(viajeEntity.LongitudOrigen));
                        GeoCoordinate driverPosition = new GeoCoordinate(driverPositionEntity.Latitud, driverPositionEntity.Longitud);
                        double        distance       = clientPosition.GetDistanceTo(driverPosition);
                        if (distance < 10000)
                        {
                            var receivers = Handler.Connections.FindAll(m => ((ChatConnection)m).SocketId == entity.Id.ToString());

                            if (receivers.Count != 0)
                            {
                                requestedDriverCnt++;
                                receivers.ForEach(async delegate(WebSocketConnection receiver)
                                {
                                    var sendMessage = JsonConvert.SerializeObject(new SendMessage
                                    {
                                        Sender   = SocketId,
                                        Type     = "new_trip_request",
                                        TripData = new NewTripRequest
                                        {
                                            PassengerName = userioEntity.Usuario.Nombre,
                                            ViajeId       = (int)viajeEntity.Id,
                                            From          = new CoordinateData
                                            {
                                                Latitud  = double.Parse(viajeEntity.LatitudOrigen),
                                                Longitud = double.Parse(viajeEntity.LongitudOrigen)
                                            },
                                            To = new CoordinateData
                                            {
                                                Latitud  = double.Parse(viajeEntity.LatitudDestino),
                                                Longitud = double.Parse(viajeEntity.LongitudDestino)
                                            }
                                        }
                                    });
                                    var chatRecevier = (ChatConnection)receiver;
                                    await chatRecevier.SendMessageAsync(sendMessage);
                                });
                            }
                            else
                            {
                                var sendMessage = JsonConvert.SerializeObject(new SendMessage
                                {
                                    Sender  = SocketId,
                                    Type    = "SocketError",
                                    Message = "Can not send new request"
                                });

                                await SendMessageAsync(sendMessage);
                            }
                        }
                    }
                }
            }
            else if (messageType == "accept_trip")      // Socket Module for accepting new trip for driver
            {
                /*
                 * Acception new trip will be triggered by conductor
                 * It will change viaje status to 2
                 * and will add data to ViajesConductor table
                 */
                var viajeConductor = new ViajeConductor
                {
                    IdConductor = int.Parse(SocketId),
                    IdViaje     = receiveMessage.ConductorData.IdViaje,
                    FechaAlta   = DateTime.Now
                };
                _context.ViajesConductores.Add(viajeConductor);
                _context.SaveChanges();
                var viajeEntity = _context.Viajes.Where(s => s.Id == receiveMessage.ConductorData.IdViaje).First <Viaje>();
                viajeEntity.EstatusViajeId = 2;
                _context.Update <Viaje>(viajeEntity);
                _context.SaveChanges();
            }
            else if (messageType == "status_trip_change")                // this socket is called when trip is canceled
            {
                /*
                 * This module is for changing status of Viaje
                 * related to cat_estatus_viajes
                 * Will be called when trip is canceled
                 * Status in SocketData will include changed status data
                 * Status can be
                 * 5: Cancelado Cliente
                 * 6: Canceloado Conductor
                 */
                var viajeEntity = _context.Viajes.Where(s => s.Id == receiveMessage.ConductorData.IdViaje).First <Viaje>();
                viajeEntity.EstatusViajeId = receiveMessage.Status;
                _context.Update <Viaje>(viajeEntity);
                _context.SaveChanges();
            }
            else if (messageType == "finish_trip")      // Socket Module for finish trip
            {
                /*
                 * This module will be called when trip is finished
                 * Finishing trip will call socket with distance and Tarifa
                 * This data will be saved to ViajeConductor
                 * and also will change viaje status to Finish(4)
                 */
                var viajeConductor = _context.ViajesConductores.Where(s => s.Id == receiveMessage.ConductorData.Id).First <ViajeConductor>();
                viajeConductor.KmRecorridos = receiveMessage.ConductorData.KmRecorridos;
                viajeConductor.Tarifa       = receiveMessage.ConductorData.Tarifa;
                _context.Update <ViajeConductor>(viajeConductor);
                _context.SaveChanges();

                var viajeEntity = _context.Viajes.Where(s => s.Id == receiveMessage.ConductorData.IdViaje).First <Viaje>();
                viajeEntity.EstatusViajeId = 4;
                _context.Update <Viaje>(viajeEntity);
                _context.SaveChanges();
            }
            else if (messageType == "get_nearby_drivers")
            {
                /*
                 * This module is for Getting NearBy drivers on Map View in client side
                 * Client Socket will request data with
                 * Type: "get_nearby_drivers"
                 * Location1: { Latitud: xxx, Longitud: xxx}
                 * Module will retrieve socket data with nearest 10 drivers in 10km
                 * with Type: "
                 *   Type = "near_by_drivers",
                 *   NearByDrivers = driverList
                 *   NearByDrivers is Array for Driver Data with {Id and Location{Latitud: xxx, Longitud: yyy}}
                 */
                var activeUsuarioEntities        = _context.CuentasUsuario.Where <CuentaUsuario>(s => s.EnServicio == true && s.IdTipoCuenta == 1);
                int requestedDriverCnt           = 0;
                List <DriverLocation> driverList = new List <DriverLocation>();
                // Finding List of drivers in 10km
                foreach (var entity in activeUsuarioEntities)
                {
                    if (requestedDriverCnt == 10)
                    {
                        break;
                    }
                    var viajeConductor = _context.ViajesConductores.Where(s => s.IdConductor == entity.Id).Last <ViajeConductor>();
                    if (viajeConductor.Viaje.EstatusViajeId == 1)
                    {
                        var driverPositionEntity = _context.VehiculoPosicion.Where(s => s.IdCuentaUsuario == entity.Id).First <VehiculoPosicion>();

                        GeoCoordinate clientPosition = new GeoCoordinate(double.Parse(receiveMessage.Location1.Latitud.ToString()), double.Parse(receiveMessage.Location1.Longitud.ToString()));
                        GeoCoordinate driverPosition = new GeoCoordinate(driverPositionEntity.Latitud, driverPositionEntity.Longitud);
                        double        distance       = clientPosition.GetDistanceTo(driverPosition);
                        if (distance < 10000)
                        {
                            // Add Driver Data to List Wit Coordinate Data
                            driverList.Add(
                                new DriverLocation
                            {
                                Id       = (int)entity.Id,
                                Location = new CoordinateData
                                {
                                    Latitud  = driverPositionEntity.Latitud,
                                    Longitud = driverPositionEntity.Longitud
                                }
                            }
                                );
                        }
                    }
                }
                var sendMessage = JsonConvert.SerializeObject(new SendMessage
                {
                    Sender        = SocketId,
                    Type          = "near_by_drivers",
                    NearByDrivers = driverList
                });
                //var chatRecevier = (ChatConnection)receiver;
                await SendMessageAsync(sendMessage);
            }
        }
示例#35
0
 public IActionResult GetViaje(Viaje viaje)
 {
     _viajesDAO.AddViaje(viaje);
     return(Created(HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + HttpContext.Request.Path + "/" + viaje.IdViaje, viaje));
 }
        private void btnIngresar_Click(object sender, EventArgs e)
        {
            if (clienteRed.Connected)
            {
                try
                {
                    //NuevoConductor = datos.ValidarUsuario(txtUsuario.Text, txtContrasena.Text);
                    //Envia solicitud de validación al Servidor
                    String mensaje = "ValidarUsuario/" + txtUsuario.Text + "/" + txtContrasena.Text;
                    clientStream = clienteRed.GetStream();
                    encoder      = new ASCIIEncoding();
                    byte[] buffer = encoder.GetBytes(mensaje);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    //Recibe Respuesta desde el Servidor
                    clientStream = clienteRed.GetStream();
                    byte[] message = new byte[4096];
                    int    bytesRead;
                    bytesRead = clientStream.Read(message, 0, 4096);
                    //message has successfully been received
                    encoder = new ASCIIEncoding();
                    System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                    String lastMessage = encoder.GetString(message, 0, bytesRead);
                    //MessageBox.Show("Mensaje recibido en cliente: " + lastMessage);
                    String[] respuesta = lastMessage.Split('/');
                    switch (respuesta[0])
                    {
                    case "noexiste":
                        MessageBox.Show("Usuario o contraseña Incorrectos", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;

                    //Si el conductor está validado recibe desde servidor los datos del usuario para usarlos en la aplicación
                    case "validado":
                        Viaje nuevoViaje = new Viaje();
                        NuevoConductor.Identificacion  = respuesta[1];
                        NuevoConductor.Nombre          = respuesta[2];
                        NuevoConductor.PrimerApellido  = respuesta[3];
                        NuevoConductor.SegundoApellido = respuesta[4];
                        NuevoConductor.Usuario         = txtUsuario.Text;
                        NuevoConductor.Contrasena      = txtContrasena.Text;
                        MessageBox.Show("Usuario correcto puede ingresar" +
                                        "\nIdentificación:" + NuevoConductor.Identificacion +
                                        "\nNombre:" + NuevoConductor.Nombre +
                                        "\nPrimer Apellido:" + NuevoConductor.PrimerApellido +
                                        "\nSegundo Apellido:" + NuevoConductor.SegundoApellido, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        frmPrincipalCliente formularioPrincipal = new frmPrincipalCliente(NuevoConductor, clienteRed, nuevoViaje);
                        formularioPrincipal.Show();
                        break;

                    case "validadoyencurso":

/*                            mensaje = "validadoyencurso" + "/" + conductorValidado.Identificacion + "/" + conductorValidado.Nombre + "/" + conductorValidado.PrimerApellido +
 *                          "/" + conductorValidado.SegundoApellido + "/" + viajeEnCurso.ViajeID + "/" + viajeEnCurso.LugarInicio + "/" + viajeEnCurso.LugarFinalizacion
 + "/" + viajeEnCurso.Carga + "/" + viajeEnCurso.TiempoEstimado + "/" + viajeEnCurso.UbicacionActual;
 */
                        Viaje viajeEnCurso = new Viaje();
                        NuevoConductor.Identificacion  = respuesta[1];
                        NuevoConductor.Nombre          = respuesta[2];
                        NuevoConductor.PrimerApellido  = respuesta[3];
                        NuevoConductor.SegundoApellido = respuesta[4];
                        NuevoConductor.Usuario         = txtUsuario.Text;
                        NuevoConductor.Contrasena      = txtContrasena.Text;
                        viajeEnCurso.ViajeID           = Convert.ToInt32(respuesta[5]);
                        viajeEnCurso.LugarInicio       = respuesta[6];
                        viajeEnCurso.LugarFinalizacion = respuesta[7];
                        viajeEnCurso.Carga             = respuesta[8];
                        viajeEnCurso.TiempoEstimado    = respuesta[9];
                        viajeEnCurso.UbicacionActual   = respuesta[10];
                        viajeEnCurso.FechaCreacion     = respuesta[11];
                        viajeEnCurso.Estado            = "en_curso";

                        MessageBox.Show("Usuario correcto puede ingresar" +
                                        "\nIdentificación:" + NuevoConductor.Identificacion +
                                        "\nNombre:" + NuevoConductor.Nombre +
                                        "\nPrimer Apellido:" + NuevoConductor.PrimerApellido +
                                        "\nSegundo Apellido:" + NuevoConductor.SegundoApellido, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        frmPrincipalCliente formularioPrincipalEnCurso = new frmPrincipalCliente(NuevoConductor, clienteRed, viajeEnCurso);
                        formularioPrincipalEnCurso.Show();
                        break;

                    case "esperando":
                        MessageBox.Show("Usuario creado pero no autorizado", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;

                    case "default":
                        MessageBox.Show("Se ha generado un error en la validación", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Ha ocurrido un error al crear al Ingresar " + ex.Message, "A", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("No existe Conexión al Servidor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //Limpia los campos del formulario
            txtUsuario.Clear();
            txtContrasena.Clear();
        }
示例#37
0
 public ViajeView(Viaje viaje)
     : this()
 {
     Viaje = viaje;
 }
示例#38
0
        private void validarCampos(out String textoError, out Viaje viaje)
        {
            textoError = "";

            if (comboOrigen.Text == null || comboOrigen.Text.Trim() == "")
            {
                textoError += "El campo Origen es obligatorio\n";
            }
            if (comboDestino.Text == null || comboDestino.Text.Trim() == "")
            {
                textoError += "El campo Destino es obligatorio\n";
            }
            if (comboAeronave.Text == null || comboAeronave.Text.Trim() == "")
            {
                textoError += "El campo Aeronave es obligatorio\n";
            }
            if (comboOrigen.SelectedItem != null && comboDestino.SelectedItem != null)
            {
                if (comboOrigen.SelectedItem.Equals(comboDestino.SelectedItem))
                {
                    textoError += "Origen y destino deben ser diferentes\n";

                }

            }
            else
            {
                textoError += "Origen y destino obligatorio\n";
            }

            if (dateTimeFechaLlegada.Value == null)
            {
                textoError += "El campo fecha de llegada es obligatorio\n";
            }
            //if (dateTimeFechaLlegada.Value.CompareTo(JanadianDateDB.Instance.getFechaSistema()) <= 0)
            //{
            //    textoError += "El campo fecha de llegada debe ser mayor a la fecha actual\n";
            //}

            viaje = null;

            if (comboAeronave.SelectedItem != null && comboOrigen.SelectedItem != null && comboDestino.SelectedItem != null && dateTimeFechaLlegada.Value != null)
            {

                Aeronave nave = JanadianDateDB.Instance.getAeronaveByMatricula(comboAeronave.SelectedItem.ToString());
                viaje = JanadianDateDB.Instance.getViaje(nave, comboOrigen.SelectedItem, comboDestino.SelectedItem);

                if (viaje == null)
                {
                    textoError += "No existe  viaje al que no le haya sido registrada la llegada para las condiciones ingresadas\nRevise si el viaje existe o si ya registro la llegada\n";

                }
                else if (viaje.getFechaLlegada.CompareTo(viaje.getFechaSalida)>0) {
                    textoError += "Ya se ha registrado la llegada de este viaje\n";

                }
            }
        }
示例#39
0
 public static int AgregarViaje(Viaje viaje)
 {
     return executeProcedureWithReturnValue("sp_generar_viaje", 1, viaje.Ruta, viaje.Aeronave, viaje.FechaSalida, viaje.FechaLlegada, viaje.FechaLlegadaEstimada); ;
 }
示例#40
0
        private void btnAgregarNuevo_Click(object sender, EventArgs e)
        {
            Viaje nuevoViaje = new Viaje();



            if (!(txtLugarInicio.Text.Equals(string.Empty) || txtLugarFinalizacion.Text.Equals(string.Empty) ||
                  txtCarga.Text.Equals(string.Empty) || txtTiempoEstimado.Text.Equals(string.Empty)))
            {
                if (clienteRed.Connected)
                {
                    try
                    {
                        //Lee los campos del formulario y los solicita al servidor el registro de Nuevo Usuario
                        //Envia solicitud de validación al Servidor
                        //Obtiene fecha de creacion
                        DateTime currentDateTime = DateTime.Now;
                        string   FechaCreacion   = currentDateTime.ToString();

                        String mensaje = "CrearViaje/" + conductorActual.Identificacion + "/" + txtLugarInicio.Text + "/" +
                                         txtLugarFinalizacion.Text + "/" + txtCarga.Text + "/" + txtTiempoEstimado.Text +
                                         "/" + FechaCreacion;
                        clientStream = clienteRed.GetStream();
                        encoder      = new ASCIIEncoding();
                        byte[] buffer = encoder.GetBytes(mensaje);
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();

                        //Recibe Respuesta desde el Servidor
                        clientStream = clienteRed.GetStream();
                        byte[] message = new byte[4096];
                        int    bytesRead;
                        bytesRead = clientStream.Read(message, 0, 4096);
                        //message has successfully been received
                        encoder = new ASCIIEncoding();
                        System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                        String lastMessage = encoder.GetString(message, 0, bytesRead);
                        //MessageBox.Show("Mensaje recibido en cliente: " + lastMessage);

                        String[] respuesta = lastMessage.Split('/');
                        switch (respuesta[0])
                        {
                        case "error":
                            MessageBox.Show("Servidor reporta error durante el registro \n" +
                                            "Consulte con el Administrador", "Información", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;

                        default:
                            nuevoViaje.ViajeID           = Convert.ToInt32(respuesta[0]);
                            nuevoViaje.Identificacion    = conductorActual.Identificacion;
                            nuevoViaje.LugarInicio       = txtLugarInicio.Text;
                            nuevoViaje.UbicacionActual   = txtLugarInicio.Text;
                            nuevoViaje.LugarFinalizacion = txtLugarFinalizacion.Text;
                            nuevoViaje.TiempoEstimado    = txtTiempoEstimado.Text;
                            nuevoViaje.Carga             = txtCarga.Text;
                            nuevoViaje.FechaCreacion     = FechaCreacion;
                            //datos.AgregarViaje(nuevoViaje);
                            //nuevoViaje = datos.ObtenerViajesActivosPorCondutor(conductorActual.Identificacion);
                            formatoViajeEnCurso(nuevoViaje);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error al intentar escribir a base de datos" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("No existe conexion al servidor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                //En caso de que los datos no estén completos se muestra un mensaje de advertencia
                //Se debe tener cuidado que no parezca un mensaje de error, dado que no es un error
                MessageBox.Show("Debe completar todos los campos!", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }