public void M10_DaoEliminar() { restaurantDao = FabricaDAO.RestaurantBD(); //Parametros para crear el nuevo registro en la base de datos ((CRestauranteModelo)restaurant).nombre = "ItalyFood"; ((CRestauranteModelo)restaurant).descripcion = "Comida Italiana"; ((CRestauranteModelo)restaurant).direccion = "Antiamano"; ((CRestauranteModelo)restaurant).Telefono = "0212-5896699"; ((CRestauranteModelo)restaurant).horarioApertura = "09:00"; ((CRestauranteModelo)restaurant).horarioCierre = "21:00"; ((CRestauranteModelo)restaurant).idLugar = 12; Resultado = restaurantDao.Crear(restaurant); //Verificar si el resultado fue exitoso Assert.AreEqual(Resultado, true); Entidad rest = FabricaEntidad.crearRestaurant(); String StringConection = restaurantDao.ConectionString(); String sqlString = "SELECT TOP 1 rst_id FROM Restaurante where fk_lugar = 12 ORDER BY rst_id DESC;"; SqlConnection conexion = new SqlConnection(StringConection); conexion.Open(); SqlCommand cmd = new SqlCommand(sqlString, conexion); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); int idRestaurant = int.Parse(reader["rst_id"].ToString()); IDAORestaurant restaurantDao1 = FabricaDAO.RestaurantBD(); restaurante._id = idRestaurant; Boolean Resultado2 = restaurantDao1.Eliminar(restaurante); //Verificar si el resultado fue exitoso Assert.AreEqual(Resultado2, true); }
/// <summary> /// Action que se encarga de guardar un vuelo /// </summary> /// <param name="model"></param> /// <returns>vista parcial</returns> public ActionResult M04_GuardarVuelo(CrearVueloMO model) { Command <Boolean> comando; Entidad vuelo; Entidad avion; Entidad ruta; try { model.setFechaDespegue(); avion = FabricaEntidad.InstanciarAvion(model._idAvion, "", "", 0, 0, 0, 0, 0, 0, 0, 0); avion._id = model._idAvion; ruta = FabricaEntidad.InstanciarRuta(model._idRuta, 0, "", "", "", ""); vuelo = FabricaEntidad.InstanciarVuelo(model._idAvion, model._codigoVuelo, (Ruta)ruta, model.fechaDespegue, model._statusVuelo, model.getFechaAterrizaje(), (Avion)avion); comando = FabricaComando.crearM04_AgregarVuelo(vuelo); comando.ejecutar(); } catch (ReservaExceptionM04 ex) { Log.EscribirError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name, ex); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(ex.Message, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(RecursoAvionCO.MensajeErrorGeneral, JsonRequestBehavior.AllowGet)); } return(RedirectToAction("M04_GestionVuelo_Visualizar")); }
/// <summary> /// Metodo para aregar un permiso nuevo /// <returns>retorna JsonResult</returns> /// </summary> public JsonResult agregarpermiso(CModulo_detallado model) { //Verifico que todos los campos no sean nulos if (model.Nombre == null && model.Url == null) { //Creo el codigo de error de respuesta Response.StatusCode = (int)HttpStatusCode.BadRequest; //Agrego mi error String error = "Error, campos obligatorios vacios"; //Retorno el error return(Json(error)); } try { Entidad nuevoPermiso = FabricaEntidad.InstanciarPermiso(model); Command <String> comando = FabricaComando.crearM13_AgregarPermiso(nuevoPermiso); String agrego_si_no = comando.ejecutar(); return(Json(agrego_si_no)); } catch (ReservaExceptionM13 ex) { return(Json(ex.Mensaje)); } }
public bool VerificarNota() { Entidad usuario = (contrato.Sesion["usuario"] as Clases.Usuario); bool estado = false; nota = FabricaEntidad.CrearNota(); (nota as Clases.Nota).Titulo = contrato.getTitulo(); (nota as Clases.Nota).Idnota = int.Parse(contrato.getIdNota()); (nota as Clases.Nota).Libreta.NombreLibreta = contrato.getNombreLibreta(); notaExiste = FabricaEntidad.CrearNota(); comandoverificar = FabricaComando.CrearComandoVerificarNota(nota, usuario); notaExiste = comandoverificar.Ejecutar(); if ((notaExiste as Clases.Nota).Idnota == 0 || (notaExiste as Clases.Nota).Idnota == (nota as Clases.Nota).Idnota) { estado = true; return(estado); } else { contrato.MensajeError.Text = _mensajeErrorInsertar; contrato.MensajeError.Visible = true; return(estado); } }
public JsonResult agregarrol(CRoles model) { //Verifico que todos los campos no sean nulos if (model.Nombre_rol == null) { //Creo el codigo de error de respuesta Response.StatusCode = (int)HttpStatusCode.BadRequest; //Agrego mi error String error = "Error, campo obligatorio vacio"; //Retorno el error return(Json(error)); } try { Entidad nuevoRol = FabricaEntidad.InstanciarRol(model); Command <String> comando = FabricaComando.crearM13_AgregarRol(nuevoRol); String agrego_si_no = comando.ejecutar(); return(Json(agrego_si_no)); } catch (ReservaExceptionM13 ex) { return(Json(new { error = ex.Mensaje })); } }
public void M10_ComandoEliminar() { restaurantDao = FabricaDAO.RestaurantBD(); //Parametros para crear el nuevo registro en la base de datos ((CRestauranteModelo)restaurant).nombre = "ItalyFood"; ((CRestauranteModelo)restaurant).descripcion = "Comida Italiana"; ((CRestauranteModelo)restaurant).direccion = "Antimano"; ((CRestauranteModelo)restaurant).Telefono = "0212-5896699"; ((CRestauranteModelo)restaurant).horarioApertura = "09:00"; ((CRestauranteModelo)restaurant).horarioCierre = "21:00"; ((CRestauranteModelo)restaurant).idLugar = 12; Command <Boolean> comando = (Command <Boolean>)FabricaComando.comandosRestaurant(FabricaComando.comandosGlobales.CREAR, BOReserva.Controllers.PatronComando.FabricaComando.comandoRestaurant.NULO, restaurant); //Verificar si el resultado fue exitoso Assert.AreEqual(comando.ejecutar(), true); Entidad rest = FabricaEntidad.crearRestaurant(); String StringConection = restaurantDao.ConectionString(); String sqlString = "SELECT TOP 1 rst_id FROM Restaurante where fk_lugar = 12 ORDER BY rst_id DESC;"; SqlConnection conexion = new SqlConnection(StringConection); conexion.Open(); SqlCommand cmd = new SqlCommand(sqlString, conexion); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); int idRestaurant = int.Parse(reader["rst_id"].ToString()); restaurante._id = idRestaurant; Command <Boolean> comando1 = (Command <Boolean>)FabricaComando.comandosRestaurant(FabricaComando.comandosGlobales.ELIMINAR, BOReserva.Controllers.PatronComando.FabricaComando.comandoRestaurant.NULO, restaurante); //Verificar si el resultado fue exitoso Assert.AreEqual(comando1.ejecutar(), true); }
public void sqlAgregarImplementoTest() { try { DAOImplemento prueba = new DAOImplemento(); Entidad implemento = FabricaEntidad.NuevoImplemento(); (implemento as Implemento).IdImplemento = 1; (implemento as Implemento).IdProducto = 1; (implemento as Implemento).Prioridad = 1; (implemento as Implemento).TipoProducto = "Tratamiento de prueba"; (implemento as Implemento).Cantidad = 2; List <Entidad> lista = new List <Entidad>(); bool ImplementoAgregado = false; Assert.IsNotNull(prueba.SqlAgregarImplemento(implemento)); DAOImplemento serverImplemento = new DAOImplemento(); ImplementoAgregado = serverImplemento.SqlAgregarImplemento(implemento); //Assert que comprueba que el objeto exista. Assert.IsNotNull(prueba.SqlAgregarImplemento(implemento)); //Assert para que los string no esten vacios Assert.IsNotEmpty((implemento as Implemento).TipoProducto); Assert.IsTrue(ImplementoAgregado); } catch (NullReferenceException e) { throw new Exception("no hay objeto", e); } }
/// <summary> /// Metodo para conocer los datos de un reclamo /// </summary> /// <param name="id">Id del comando a consultar</param> /// <returns>Entidad que podra ser casteada a Reclamo con los datos del mismo</returns> public new Entidad Consultar(int id) { List <Parametro> parametro = FabricaDAO.asignarListaDeParametro(); int rec_id, rec_estatus, rec_fk_usuario; String rec_titulo, rec_descripcion, rec_fecha; Entidad reclamoE = FabricaEntidad.InstanciarReclamo(); Reclamo reclamo = (Reclamo)reclamoE; try { parametro.Add(FabricaDAO.asignarParametro(M16Reclamos.rec_id, SqlDbType.Int, id.ToString(), false)); DataTable filaReclamo = EjecutarStoredProcedureTuplas(M16Reclamos.procedimientoConsultarReclamoPorId, parametro); DataRow Fila = filaReclamo.Rows[0]; rec_id = int.Parse(Fila[M16Reclamos.recId].ToString()); rec_estatus = int.Parse(Fila[M16Reclamos.recEstatus].ToString()); rec_fk_usuario = int.Parse(Fila[M16Reclamos.recFkUsuario].ToString()); rec_titulo = Fila[M16Reclamos.rectitulo].ToString(); rec_descripcion = Fila[M16Reclamos.recDescripcion].ToString(); String[] divisor = Fila[M16Reclamos.recFecha].ToString().Split(' '); rec_fecha = divisor[0]; reclamo = (Reclamo)FabricaEntidad.InstanciarReclamo(rec_id, rec_titulo, rec_descripcion, rec_fecha, rec_estatus, rec_fk_usuario); return(reclamo); } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); return(null); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(null); } }
/// <summary> /// Método para consultar un reclamo en la BD /// </summary> /// <param name="id">id del reclamo a consultar</param> /// <returns> reclamo conseguido</returns> Entidad IDAO.Consultar(int id) { List <Parametro> parametro = FabricaDAO.asignarListaDeParametro(); int rec_id, rec_fk_pasajero, rec_fk_equipaje; String rec_descripcion, rec_fecha, rec_status; Entidad reclamoE = FabricaEntidad.InstanciarReclamoEquipaje(); ReclamoEquipaje reclamo = (ReclamoEquipaje)reclamoE; try { parametro.Add(FabricaDAO.asignarParametro(M07ReclamoEquipaje.rec_id, SqlDbType.Int, id.ToString(), false)); DataTable filaReclamo = EjecutarStoredProcedureTuplas(M07ReclamoEquipaje.procedimientoConsultarReclamoPorID, parametro); DataRow Fila = filaReclamo.Rows[0]; rec_id = int.Parse(Fila[M07ReclamoEquipaje.recId].ToString()); rec_status = Fila[M07ReclamoEquipaje.recStatus].ToString(); rec_fk_pasajero = int.Parse(Fila[M07ReclamoEquipaje.recFkPasajero].ToString()); rec_fk_equipaje = int.Parse(Fila[M07ReclamoEquipaje.recFkEquipaje].ToString()); rec_descripcion = Fila[M07ReclamoEquipaje.recDescripcion].ToString(); String[] divisor = Fila[M07ReclamoEquipaje.recFecha].ToString().Split(' '); rec_fecha = divisor[0]; reclamo = (ReclamoEquipaje)FabricaEntidad.InstanciarReclamoEquipaje(rec_id, rec_descripcion, rec_fecha, rec_status, rec_fk_pasajero, rec_fk_equipaje); return(reclamo); } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); return(null); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(null); } }
public JsonResult guardarOferta(CAgregarOferta model, string estadoOferta) { if (estadoOferta == "1") { model._estadoOferta = true; } else { model._estadoOferta = false; } //Chequeo si los campos obligatorios estan vacios como medida de seguridad if ((model._nombreOferta == null) || (model._porcentajeOferta == 0) || (model._fechaIniOferta == null) || (model._fechaFinOferta == null)) { //Creo el codigo de error de respuesta (OJO: AGREGAR EL USING DE SYSTEM.NET) Response.StatusCode = (int)HttpStatusCode.BadRequest; //Agrego mi error String error = "Error: Campo obligatorio vacio"; //Retorno el error return(Json(error)); } if (model._fechaFinOferta.Date < model._fechaIniOferta.Date) { Response.StatusCode = (int)HttpStatusCode.BadRequest; String Error = "Error: La fecha de Inicio no puede ser igual a la fecha Fin"; return(Json(Error)); } Entidad nuevaOferta = FabricaEntidad.InstanciarOferta(model); //con la fabrica instancie la oferta. Command <String> comando = FabricaComando.crearM11AgregarOferta(nuevaOferta); String agrego_si_no = comando.ejecutar(); return(Json(agrego_si_no)); }
public JsonResult guardarRestaurante(String Nombre, String Direccion, String Telefono, String Descripcion, int idLugar, String HoraIni, String HoraFin) { //Las variables se reciben de esta forma para asemejar los mas posible a la Arquitectura MVC tradicional //Chequeo de campos obligatorios para el formulario if ((Nombre == "") || (Direccion == "") || (HoraIni == "Horario Inicio") || (Telefono == "") || (HoraFin == "Horario Fin") || (idLugar == 0)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; string error = "Error, existen campos vacios"; return(Json(error)); } try { Entidad _restaurant = FabricaEntidad.crearRestaurant(Nombre, Direccion, Telefono, Descripcion, HoraIni, HoraFin, idLugar); Command <Boolean> comando = (Command <Boolean>)FabricaComando.comandosRestaurant(FabricaComando.comandosGlobales.CREAR, BOReserva.Controllers.PatronComando.FabricaComando.comandoRestaurant.NULO, _restaurant); if (comando.ejecutar()) { return(Json(true, JsonRequestBehavior.AllowGet)); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; string error = "Error agregando el restaurante."; return(Json(error)); } } catch (Exception) { Response.StatusCode = (int)HttpStatusCode.BadRequest; string error = "Error de Conexion BD"; return(Json(error)); } }
/// <summary> /// Constructor de la clase /// </summary> /// <param name="id">Id del itinerario</param> public ComandoEliminarItinerario(int id) { itinerario = FabricaEntidad.CrearEntidadItinerario(); itinerario.Id = id; }
/// <summary> /// Genera el Boleto de la reserva /// </summary> /// <param name="id_reserva"></param> /// <returns></returns> public ActionResult M05_BoletoCreadoReserva(int id_reserva) { //BUSCA LA RESERVA A MOSTRA //Uso Boleto ya que tiene los mismos atributos de reserva_bolet Command <Entidad> comando = FabricaComando.consultarM05BoletopasajeroBD(id_reserva); Boleto reserva = (Boleto)comando.ejecutar(); // EL/LOS VUELOS DEL BOLETO ESTAN EN UNA LISTA // NO SOPORTA ESCALAS List <BoletoVuelo> vuelos = reserva._vuelos; CVisualizarBoleto bol = new CVisualizarBoleto(); if (reserva._ida_vuelta == 1) { var time = vuelos[0]._fechaPartida.TimeOfDay.ToString(); var time1 = vuelos[0]._fechaLlegada.TimeOfDay.ToString(); bol._fechaDespegueIda = vuelos[0]._fechaPartida.Day + "/" + vuelos[0]._fechaPartida.Month + "/" + vuelos[0]._fechaPartida.Year; bol._fechaDespegueVuelta = ""; bol._fechaAterrizajeIda = vuelos[0]._fechaLlegada.Day + "/" + vuelos[0]._fechaLlegada.Month + "/" + vuelos[0]._fechaLlegada.Year; bol._fechaAterrizajeVuelta = ""; bol._horaDespegueIda = time; bol._horaDespegueVuelta = ""; bol._horaAterrizajeIda = time1; bol._horaAterrizajeVuelta = ""; } else { var time0 = vuelos[0]._fechaPartida.TimeOfDay.ToString(); var time1 = vuelos[0]._fechaLlegada.TimeOfDay.ToString(); var time2 = vuelos[1]._fechaPartida.TimeOfDay.ToString(); var time3 = vuelos[1]._fechaLlegada.TimeOfDay.ToString(); bol._fechaDespegueIda = vuelos[0]._fechaPartida.Day + "/" + vuelos[0]._fechaPartida.Month + "/" + vuelos[0]._fechaPartida.Year; bol._fechaDespegueVuelta = vuelos[1]._fechaPartida.Day + "/" + vuelos[1]._fechaPartida.Month + "/" + vuelos[1]._fechaPartida.Year; bol._fechaAterrizajeIda = vuelos[0]._fechaLlegada.Day + "/" + vuelos[0]._fechaLlegada.Month + "/" + vuelos[0]._fechaLlegada.Year; bol._fechaAterrizajeVuelta = vuelos[1]._fechaLlegada.Day + "/" + vuelos[1]._fechaLlegada.Month + "/" + vuelos[1]._fechaLlegada.Year; bol._horaDespegueIda = time0; bol._horaDespegueVuelta = time1; bol._horaAterrizajeIda = time2; bol._horaAterrizajeVuelta = time3; } bol._origen = reserva._origen.Name; bol._destino = reserva._destino.Name; bol._monto = reserva._costo; bol._tipoBoleto = reserva._tipoBoleto; bol._nombre = reserva._pasajero._primer_nombre; bol._apellido = reserva._pasajero._primer_apellido; bol._pasaporte = reserva._pasajero._id; bol._correo = reserva._pasajero._correo; bol._idReserva = id_reserva; int id_origen = reserva._origen.Id; int id_destino = reserva._destino.Id; double dcosto = reserva._costo; int costo = (int)dcosto; //Tomo todos los datos de bol para crear el boleto //Creo método para crear el boleto en el servicio y le paso por parámetro los atributos //(bol_id,bol_escala,bol_ida_vuelta,bol_costo,fk_origen,fk_destino,fk_pasajero,bol_fecha,tipo_boleto) int id_vuelo = reserva._vuelos[0]._id; System.Diagnostics.Debug.WriteLine("EL ID DEL VUELO DE LA RESERVA ES: " + id_vuelo); String fecha_bol = DateTime.Today.ToString("yyyy/MM/dd"); Boleto nuevoBoleto = (Boleto)FabricaEntidad.InstanciarBoleto(id_origen, id_destino, reserva._pasajero._id, costo, reserva._tipoBoleto, id_vuelo, fecha_bol); Command <String> comando2 = FabricaComando.crearM05CrearBoleto(nuevoBoleto); string flag = comando2.ejecutar(); System.Diagnostics.Debug.WriteLine("Finaliza el controller"); return(PartialView(bol)); }
/// <summary> /// Metodo Get para obtener los lugares turisticos /// </summary> /// <param name="cantidad"></param> /// <returns>JObject</returns> public override JObject Get(int cantidad) { LugarTuristico lugarTuristico = FabricaEntidad.GetLugarTuristico(); lugarTuristico.Id = cantidad; try { using (HttpClient cliente = new HttpClient()) { cliente.BaseAddress = new Uri(BaseUri); cliente.DefaultRequestHeaders.Accept.Clear(); var responseTask = cliente.PostAsJsonAsync($"{BaseUri}/{ControllerUri}/ListaLugaresTuristicosDetallados", lugarTuristico); responseTask.Wait(); var response = responseTask.Result; var readTask = response.Content.ReadAsAsync <JObject>(); readTask.Wait(); responseData = readTask.Result; return(responseData); } } catch (HttpRequestException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (WebException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (SocketException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (AggregateException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (JsonSerializationException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (JsonReaderException ex) { responseData = new JObject { { "error", ex.Message } }; } catch (Exception ex) { responseData = new JObject { { "error", $"Ocurrio un error inesperado: {ex.Message}" } }; } return(responseData); }
public ComandoConsultarMiembroSinLider(int id) { grupo = FabricaEntidad.CrearEntidadGrupo(); grupo.Id = id; }
public ComandoConsultarListaGrupos(int id) { usuario = FabricaEntidad.CrearEntidadUsuario(); usuario.Id = id; }
/// <summary> /// Procedimiento que consulta el detalle de una oferta en la base de datos /// </summary> /// <param name="id">Id de la oferta</param> /// <returns>Una entidad del tipo oferta</returns> Entidad IDAO.Consultar(int id) { Debug.WriteLine("LLEGÓ A DAO CONSULTAROFERTA"); SqlConnection conexion = Connection.getInstance(_connexionString); Entidad oferta = null; Int32 _id; _id = id; try { conexion.Open(); SqlCommand cmd = new SqlCommand("[dbo].[M11_ConsultarOferta]", conexion); cmd.CommandType = CommandType.StoredProcedure; Debug.WriteLine("HIZO CONEXIÓN EN VISUAL"); Debug.WriteLine(id); Debug.WriteLine(_id); SqlParameter ParId = new SqlParameter(); ParId.ParameterName = "@ofer_id"; ParId.SqlDbType = SqlDbType.Int; ParId.Value = id; //SqlCmd.Parameters.Add(ParNombre); cmd.Parameters.Add(ParId); Debug.WriteLine("HIZO LA PARTED E PARÁMETRO"); using (SqlDataReader reader = cmd.ExecuteReader()) { Debug.WriteLine("CMD.READER EN CONSULTAR"); while (reader.Read()) { var fechaInivar = reader["fechaIn"]; var fechaFinvar = reader["fechaFin"]; var estadovar = reader["estado"]; DateTime fechaInicio = Convert.ToDateTime(fechaInivar).Date; DateTime fechaFin = Convert.ToDateTime(fechaFinvar).Date; Boolean disponibilidad = Convert.ToBoolean(estadovar); Debug.WriteLine("FECHAINI" + fechaInicio); List <String> listaPaquetes = new List <String>(); // listaPaquetes = MBuscarNombrePaquetesDeOferta(Int32.Parse(reader["ofe_ID"].ToString())); oferta = FabricaEntidad.InstanciarOferta(Int32.Parse(reader["idOferta"].ToString()), reader["nombreOferta"].ToString(), listaPaquetes, float.Parse(reader["porcentaje"].ToString()), fechaInicio, fechaFin, disponibilidad); } cmd.Dispose(); conexion.Close(); return(oferta); } } catch (SqlException ex) { conexion.Close(); return(null); } }
/// <summary> /// Constructor de la clase /// </summary> /// <param name="idUsuario">Id del usuario</param> public ComandoConsultarNotificacion(int idUsuario) { notificacion = FabricaEntidad.CrearEntidadNotificacion(); notificacion.IdUsuario = idUsuario; }
//Patron Aplicado #region Consultar Tratamiento No Asociado public List <Entidad> ConsultarTratamientoNoAsociado(int _idTratamiento) { //Se instancia un objeto conexion SqlDataReader reader = null; List <Entidad> miListaTratamiento = new List <Entidad>(); Entidad _tratamiento; try { //Se abre la conexion a la base de datos _conexion.AbrirConexion(); command.Connection = _conexion.ObjetoConexion(); command.CommandType = System.Data.CommandType.StoredProcedure; command.CommandText = "dbo.[ConsultarTratamientosNoAsociados]"; command.CommandTimeout = 10; command.Parameters.AddWithValue("@idTratamiento", _idTratamiento); //se ejecuta el metodo del store procedure que busca todos los clientes del sistema reader = command.ExecuteReader(); //Se recorre cada row while (reader.Read()) { _tratamiento = FabricaEntidad.NuevoTratamiento(); //Se asigna cada atributo al objeto tratamiento (_tratamiento as Tratamiento).Id = Convert.ToInt16(reader.GetValue(0)); (_tratamiento as Tratamiento).Nombre = reader.GetValue(1).ToString(); //se inserta el cliente en la lista de tratamientos miListaTratamiento.Add(_tratamiento); } reader.Close(); //return miListaTratamiento; } catch (ArgumentException e) { throw new ExcepcionTratamiento("Parametros invalidos", e); } catch (SqlException e) { throw new ExcepcionTratamiento("Error en la conexion", e); } catch (NullReferenceException e) { throw new ExcepcionTratamiento("Tratamiento no encontrado", e); } catch (Exception e) { throw new ExcepcionTratamiento("Error", e); } finally { _conexion.CerrarConexion(); // cerramos la conexion } if (miListaTratamiento.Count == 0) { return(null); } else { return(miListaTratamiento); } }
protected void OTSU() { _categoria = FabricaEntidad.CrearEntidadCategoria(); dao = FabricaDAO.CrearDAOCategoria(); }
/// <summary> /// Método ConsultarListaPorCategoria, consulta todos los eventos filtrados por una categoria y /// los retorna en una lista. /// </summary> /// <param name="objeto"> Entidad(categoria) para filtrar la lista</param> public List <Entidad> ConsultarListaPorCategoria(Entidad objeto) { lista = new List <Entidad>(); Entidad categoria = (Categoria)objeto; try { Conectar(); Comando = SqlConexion.CreateCommand(); Comando.CommandText = "ConsultarEventosPorIdCategoria"; Comando.CommandType = CommandType.StoredProcedure; parametro = new NpgsqlParameter(); parametro.NpgsqlDbType = NpgsqlDbType.Integer; parametro.Value = categoria.Id; Comando.Parameters.Add(parametro); leerDatos = Comando.ExecuteReader(); while (leerDatos.Read()) { evento = FabricaEntidad.CrearEntidadEvento(); DateTime horaInicio = new DateTime(); horaInicio = horaInicio.AddHours(leerDatos.GetTimeSpan(6).Hours); horaInicio = horaInicio.AddMinutes(leerDatos.GetTimeSpan(6).Minutes); horaInicio = horaInicio.AddSeconds(leerDatos.GetTimeSpan(6).Seconds); DateTime horaFin = new DateTime(); horaFin = horaFin.AddHours(leerDatos.GetTimeSpan(7).Hours); horaFin = horaFin.AddMinutes(leerDatos.GetTimeSpan(7).Minutes); horaFin = horaFin.AddSeconds(leerDatos.GetTimeSpan(7).Seconds); ((Evento)evento).Id = leerDatos.GetInt32(0); ((Evento)evento).Nombre = leerDatos.GetString(1); ((Evento)evento).Descripcion = leerDatos.GetString(2); ((Evento)evento).Precio = leerDatos.GetDouble(3); ((Evento)evento).FechaInicio = leerDatos.GetDateTime(4); ((Evento)evento).FechaFin = leerDatos.GetDateTime(5); ((Evento)evento).HoraInicio = horaInicio; ((Evento)evento).HoraFin = horaFin; ((Evento)evento).Foto = leerDatos.GetString(8); ((Evento)evento).IdLocalidad = leerDatos.GetInt32(9); ((Evento)evento).IdCategoria = categoria.Id; lista.Add(evento); } } catch (NpgsqlException e) { BaseDeDatosExcepcion ex = new BaseDeDatosExcepcion(e); ex.NombreMetodos = this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name; throw ex; } catch (InvalidCastException e) { CasteoInvalidoExcepcion ex = new CasteoInvalidoExcepcion(e); ex.NombreMetodos = this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name; throw ex; } catch (InvalidOperationException e) { OperacionInvalidaExcepcion ex = new OperacionInvalidaExcepcion(e); ex.NombreMetodos.Add(this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name); throw ex; } catch (Exception ex) { throw ex; } finally { Desconectar(); } return(lista); }
public void ProbarDaoUsuarioConsultarPorId() { usuario = FabricaEntidad.CrearEntidadUsuario(500); respuesta = dao.ConsultarPorId(usuario); Assert.AreEqual(usuario.Id, respuesta.Id); }
//Listo Patron Aplicado #region Consultar Tratamiento por Estado public List <Entidad> SqlBuscarXEstadoTramiento(string estadoTratamientoBuscar) { //Se instancia un objeto conexion command = new SqlCommand(); SqlDataReader reader = null; List <Entidad> miListaTratamiento = new List <Entidad>(); Entidad _tratamiento; try { //Se abre la conexion a la base de datos _conexion.AbrirConexion(); command.Connection = _conexion.ObjetoConexion(); command.CommandType = System.Data.CommandType.StoredProcedure; command.CommandText = "dbo.BuscarXEstadoTratamiento"; command.Parameters.AddWithValue("@EstadoTratamiento", estadoTratamientoBuscar); reader = command.ExecuteReader(); //Se recorre cada Fila while (reader.Read()) { _tratamiento = FabricaEntidad.NuevoTratamiento(); //Se asigna cada atributo al objeto tratamiento (_tratamiento as Tratamiento).Id = Convert.ToInt16(reader.GetValue(0)); (_tratamiento as Tratamiento).Nombre = reader.GetValue(1).ToString(); (_tratamiento as Tratamiento).Duracion = Convert.ToInt16(reader.GetValue(2)); (_tratamiento as Tratamiento).Descripcion = reader.GetValue(3).ToString(); (_tratamiento as Tratamiento).Costo = Convert.ToInt16(reader.GetValue(4)); (_tratamiento as Tratamiento).Imagen = reader.GetValue(5).ToString(); (_tratamiento as Tratamiento).Explicacion = reader.GetValue(6).ToString(); (_tratamiento as Tratamiento).Estado = reader.GetValue(7).ToString(); miListaTratamiento.Add(_tratamiento); } reader.Close(); //return miListaTratamiento; } catch (ArgumentException e) { throw new ExcepcionTratamiento("Parametros invalidos", e); } catch (NullReferenceException e) { throw new ExcepcionTratamiento("Tratamientos no econtrados", e); } catch (SqlException e) { throw new ExcepcionTratamiento("Error con la Base de Datos", e); } catch (Exception e) { throw new ExcepcionTratamiento("Error en la Busqueda de los datos", e); } finally { _conexion.CerrarConexion(); // cerramos la conexion } if (miListaTratamiento.Count == 0) { return(null); } else { return(miListaTratamiento); } }
public void ProbarDaoUsuarioConsultarPorNombre() { usuario = FabricaEntidad.CrearEntidadUsuario("usuario1T", "123456"); //inicia usuario con su nombreUsuario y clave respuesta = ((DAOUsuario)dao).ConsultarPorNombre(usuario); Assert.AreEqual(((Usuario)usuario).Nombre, ((Usuario)respuesta).Nombre); }
/// <summary> /// Metodo implementado de IDAO para consultar los ofertas de la BD /// </summary> /// <returns>Retorna el listado de hoteles</returns> List <Entidad> IDAOOferta.ConsultarTodos() { Debug.WriteLine("LLEGÓ A DAO OFERTA"); List <Entidad> listaOfertas = FabricaEntidad.asignarListaDeEntidades(); SqlConnection conexion = Connection.getInstance(_connexionString); Entidad oferta; try { conexion.Open(); SqlCommand cmd = new SqlCommand("[dbo].[M11_ConsultarOfertas]", conexion); cmd.CommandType = CommandType.StoredProcedure; Debug.WriteLine("HIZO CONEXIÓN"); using (SqlDataReader reader = cmd.ExecuteReader()) { Debug.WriteLine("CMD.READER"); while (reader.Read()) { var fechaInivar = reader["fechaIn"]; var fechaFinvar = reader["fechaFin"]; var estadovar = reader["estado"]; DateTime fechaInicio = Convert.ToDateTime(fechaInivar).Date; DateTime fechaFin = Convert.ToDateTime(fechaFinvar).Date; Boolean disponibilidad = Convert.ToBoolean(estadovar); List <String> listaPaquetes = new List <String>(); // listaPaquetes = MBuscarNombrePaquetesDeOferta(Int32.Parse(reader["ofe_id"].ToString())); oferta = FabricaEntidad.InstanciarOferta(Int32.Parse(reader["idOferta"].ToString()), reader["nombreOferta"].ToString(), listaPaquetes, float.Parse(reader["porcentaje"].ToString()), fechaInicio, fechaFin, disponibilidad); listaOfertas.Add(oferta); } } cmd.Dispose(); conexion.Close(); return(listaOfertas); } catch (SqlException ex) { Debug.WriteLine("Ocurrio un SqlException"); Debug.WriteLine(ex.ToString()); conexion.Close(); return(null); } catch (NullReferenceException ex) { Debug.WriteLine("Ocurrio una NullReferenceException"); Debug.WriteLine(ex.ToString()); conexion.Close(); return(null); } catch (ArgumentNullException ex) { Debug.WriteLine("Ocurrio una ArgumentNullException"); Debug.WriteLine(ex.ToString()); conexion.Close(); return(null); } catch (Exception ex) { Debug.WriteLine("Ocurrio una Exception"); Debug.WriteLine(ex.ToString()); conexion.Close(); return(null); } }
public void ProbarDaoUsuarioEliminar() { usuario = FabricaEntidad.CrearEntidadUsuario("usuario1T", "123456"); //inicia usuario con su nombreUsuario y clave dao.Eliminar(usuario); Assert.DoesNotThrow(() => dao.Eliminar(usuario)); }
public Entidad ImportarConfiguracion(Entidad usuario) { XmlFile xmlFile = XmlFile.getInstancia(usuario.Estado); // Create an isntance of XmlTextReader and call Read method to read the file XmlTextReader textReader = new XmlTextReader(xmlFile.getXmlFolderPath()); textReader.Read(); // If the node has value textReader.WhitespaceHandling = WhitespaceHandling.None; Boolean seccionLibretas = false; int i = -1; int j = -1; int k = -1; while (textReader.Read()) { if (seccionLibretas == false) { if (textReader.Name.Equals("Correo")) { textReader.Read(); (usuario as Usuario).Correo = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("Clave")) { textReader.Read(); (usuario as Usuario).Clave = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("Nombre")) { Console.WriteLine("Name:" + textReader.Name); textReader.Read(); Console.WriteLine("Value:" + textReader.Value); (usuario as Usuario).Nombre = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("Apellido")) { Console.WriteLine("Name:" + textReader.Name); textReader.Read(); Console.WriteLine("Value:" + textReader.Value); (usuario as Usuario).Apellido = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("AccesSecret")) { textReader.Read(); (usuario as Usuario).AccesSecret = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("AccesToken")) { //Console.WriteLine("Name:" + textReader.Name); textReader.Read(); //Console.WriteLine("Value:" + textReader.Value); (usuario as Usuario).AccesToken = textReader.Value; textReader.Read(); } } else { if (textReader.Name.Equals("NombreLibreta")) { i++; j = -1; textReader.Read(); Entidad libreta = FabricaEntidad.CrearLibreta(); (libreta as Libreta).NombreLibreta = textReader.Value; (usuario as Usuario).ListaLibretas.Add((libreta as Libreta)); textReader.Read(); seccionLibretas = true; } if (textReader.Name.Equals("Titulo")) { j++; textReader.Read(); Entidad nota = FabricaEntidad.CrearNota(); (nota as Nota).Titulo = textReader.Value; (usuario as Usuario).ListaLibretas[i].ListaNota.Add((nota as Nota)); textReader.Read(); } if (textReader.Name.Equals("Contenido")) { textReader.Read(); (usuario as Usuario).ListaLibretas[i].ListaNota[j].Contenido = textReader.Value; textReader.Read(); } if (textReader.Name.Equals("Fechacreacion")) { textReader.Read(); (usuario as Usuario).ListaLibretas[i].ListaNota[j].Fechacreacion = Convert.ToDateTime(textReader.Value); textReader.Read(); } if (textReader.Name.Equals("Fechamodificacion")) { textReader.Read(); if (textReader.Value.Contains("/")) { (usuario as Usuario).ListaLibretas[i].ListaNota[j].Fechacreacion = Convert.ToDateTime(textReader.Value); } textReader.Read(); } if (textReader.Name.Equals("Etiquetas")) { textReader.Read(); } if (textReader.Name.Equals("NombreEtiqueta")) { Console.WriteLine("Name:" + textReader.Name); textReader.Read(); Console.WriteLine("Value:" + textReader.Value); Entidad etiqueta = FabricaEntidad.CrearEtiqueta(); (etiqueta as Etiqueta).Nombre = textReader.Value; (usuario as Usuario).ListaLibretas[i].ListaNota[j].ListaEtiqueta.Add((etiqueta as Etiqueta)); textReader.Read(); } if (textReader.Name.Equals("Adjuntos")) { textReader.Read(); k = -1; } if (textReader.Name.Equals("NombreArchivo")) { k++; textReader.Read(); Entidad adjunto = FabricaEntidad.CrearAdjunto(); (adjunto as Adjunto).Titulo = textReader.Value; (usuario as Usuario).ListaLibretas[i].ListaNota[j].ListaAdjunto.Add((adjunto as Adjunto)); textReader.Read(); } if (textReader.Name.Equals("Urlarchivo")) { textReader.Read(); if (textReader.Value != "") { (usuario as Usuario).ListaLibretas[i].ListaNota[j].ListaAdjunto[k].Urlarchivo = textReader.Value; } textReader.Read(); } } if (textReader.Name.Equals("Libretas")) { textReader.Read(); seccionLibretas = true; } } return(usuario); }
public void ProbarDaoUsuarioObtenerPassword() { usuario = FabricaEntidad.CrearEntidadUsuario("usuario1T", "123456"); respuesta = ((DAOUsuario)dao).ObtenerPassword(usuario); Assert.AreEqual(((Usuario)usuario).Clave, ((Usuario)respuesta).Clave); }
/// <summary> /// Constructor de la clase /// </summary> /// <param name="idUsuario">Id del usuario</param> public ComandoEnviarCorreoItinerario(int idUsuario) { usuario = FabricaEntidad.CrearEntidadUsuario(); dAONotificacion = FabricaDAO.CrearDAONotifiacacion(); usuario.Id = idUsuario; }
public List <Entidad> ConsultarTodosEmpleados(string nombreProcedimiento) { SqlCommand cmd = new SqlCommand(); SqlDataReader dr; List <Entidad> _empleados = new List <Entidad>(); Entidad _empleado; try { conexion.AbrirConexion(); //cmd = new SqlCommand("dbo.ListaEmpleadoActivos", conexion.ObjetoConexion()); cmd = new SqlCommand("dbo." + nombreProcedimiento, conexion.ObjetoConexion()); cmd.CommandType = CommandType.StoredProcedure; dr = cmd.ExecuteReader(); while (dr.Read()) { _empleado = FabricaEntidad.NuevoEmpleado(); (_empleado as Empleado).IdUsuario = int.Parse(dr.GetValue(0).ToString()); (_empleado as Empleado).Login = dr.GetValue(1).ToString(); (_empleado as Empleado).Password = dr.GetValue(2).ToString(); (_empleado as Empleado).PrimerNombre = dr.GetValue(5).ToString(); (_empleado as Empleado).SegundoNombre = dr.GetValue(6).ToString(); (_empleado as Empleado).PrimerApellido = dr.GetValue(7).ToString(); (_empleado as Empleado).SegundoApellido = dr.GetValue(8).ToString(); (_empleado as Empleado).FechaNace = (System.DateTime)dr.GetValue(10); (_empleado as Empleado).Sexo = dr.GetValue(11).ToString(); (_empleado as Empleado).Correo = dr.GetValue(12).ToString(); (_empleado as Empleado).TipoIdentificacion = dr.GetValue(3).ToString(); (_empleado as Empleado).Identificacion = dr.GetValue(4).ToString(); //Lleno la direccion completa (_empleado as Empleado).Direccion = (detalle as Direccion); //Detalle (_empleado as Empleado).Direccion.Id = int.Parse(dr.GetValue(19).ToString()); (_empleado as Empleado).Direccion.Nombre = dr.GetValue(20).ToString(); System.Diagnostics.Debug.WriteLine(int.Parse(dr.GetValue(19).ToString()) + dr.GetValue(20).ToString()); //Ciudad (_empleado as Empleado).Direccion.Fk_dir.Id = int.Parse(dr.GetValue(21).ToString()); (_empleado as Empleado).Direccion.Fk_dir.Ciudad = dr.GetValue(22).ToString(); System.Diagnostics.Debug.WriteLine(int.Parse(dr.GetValue(21).ToString()) + dr.GetValue(22).ToString()); //Estado (_empleado as Empleado).Direccion.Fk_dir.Fk_dir.Id = int.Parse(dr.GetValue(23).ToString()); (_empleado as Empleado).Direccion.Fk_dir.Fk_dir.Estado = dr.GetValue(24).ToString(); System.Diagnostics.Debug.WriteLine(int.Parse(dr.GetValue(23).ToString()) + dr.GetValue(24).ToString()); //Pais (_empleado as Empleado).Direccion.Fk_dir.Fk_dir.Fk_dir.Id = int.Parse(dr.GetValue(25).ToString()); (_empleado as Empleado).Direccion.Fk_dir.Fk_dir.Fk_dir.Pais = dr.GetValue(26).ToString(); System.Diagnostics.Debug.WriteLine(int.Parse(dr.GetValue(25).ToString()) + dr.GetValue(26).ToString()); //private DateTime fechaNace; //private DateTime fechaRegistro; //objetoEmpleado.Telefono = dr.GetValue().ToString(); (_empleado as Empleado).Estado = dr.GetValue(16).ToString(); (_empleado as Empleado).Sueldo = (float)dr.GetValue(17); (_empleado as Empleado).Especialidad = dr.GetValue(18).ToString(); _empleados.Add(_empleado); } conexion.CerrarConexion(); } catch (ArgumentException e) { throw new ExcepcionEmpleado("Parametros invalidos", e); } catch (InvalidOperationException e) { throw new ExcepcionEmpleado("Operacion Invalida", e); } catch (NullReferenceException e) { throw new ExcepcionEmpleado("Empleado no encontrado", e); } catch (SqlException e) { throw new ExcepcionEmpleado("Error con la Base de Datos", e); } catch (Exception e) { throw new ExcepcionEmpleado("Error General", e); } finally { conexion.CerrarConexion(); } return(_empleados); }