コード例 #1
0
        /// <summary>
        /// Permite modificar una entidad(Ciudades) en la base de datos.
        /// </summary>
        /// <param name = "ciudades"> Es la entidad(Ciudades) que se desea modificar.</param>
        private static bool Modificar(Ciudades ciudades)
        {
            bool     modificado = false;
            Contexto contexto   = new Contexto();

            try
            {
                contexto.Entry(ciudades).State = EntityState.Modified;
                modificado = contexto.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                contexto.Dispose();
            }

            return(modificado);
        }
コード例 #2
0
        private static bool Modificar(Ciudades ciudad)
        {
            Contexto contexto = new Contexto();
            bool     paso     = false;

            try
            {
                contexto.Entry(ciudad).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                paso = contexto.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                contexto.Dispose();
            }

            return(paso);
        }
コード例 #3
0
        private static bool Insertar(Ciudades ciudades)
        {
            bool     paso     = false;
            Contexto contexto = new Contexto();

            try
            {
                contexto.ciudades.Add(ciudades);
                paso = contexto.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                contexto.Dispose();
            }

            return(paso);
        }
コード例 #4
0
 private void BuscarButton_Click(object sender, RoutedEventArgs e)
 {
     if (!CiudadesBLL.Existe(Convert.ToInt32(CiudadIdTextbox.Text)))
     {
         MessageBox.Show("Error, ciudad no encontrada. \nLo sentimos, la ciudad no existe en la base de datos.", "Fallo", MessageBoxButton.OK, MessageBoxImage.Warning);
         Limpiar();
     }
     else
     {
         var ciudad = CiudadesBLL.Buscar(Convert.ToInt32(CiudadIdTextbox.Text));
         if (ciudad != null)
         {
             this.ciudad = ciudad;
         }
         else
         {
             this.ciudad = new Ciudades();
         }
         this.DataContext = this.ciudad;
     }
 }
コード例 #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtCodigo.Text.Trim() != "" && txtPrecioBasePorKg.Text.Trim() != "" && txtPrecioBasePorPasaje.Text.Trim() != "" &&
                cmbDestino.Text.Trim() != "" && cmbOrigen.Text.Trim() != "" && cmbTipoServicio.Text.Trim() != "")
            {
                string query;
                try
                {
                    int   codigo   = int.Parse(txtCodigo.Text);
                    float kgs      = float.Parse(txtPrecioBasePorKg.Text);
                    float pasaje   = float.Parse(txtPrecioBasePorPasaje.Text);
                    int   destino  = Ciudades.obtenerID(cmbDestino.Text);
                    int   origen   = Ciudades.obtenerID(cmbOrigen.Text);
                    int   servicio = TiposServicios.obtenerID(cmbTipoServicio.Text);
                    query = "EXEC JUST_DO_IT.almacenarRuta " + codigo + ", " + kgs + ", " + pasaje + ", " + origen + ", " +
                            destino + ", " + servicio;
                }
                catch (Exception)
                {
                    MessageBox.Show("Debe ingresar datos validos");
                    return;
                }

                try
                {
                    Server.getInstance().realizarQuery(query);
                    MessageBox.Show("La ruta se agrego satisfactoriamente");
                    new Vistas_Inicio.Inicio_Admin().Show();
                    this.Hide();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Debe completar todos los campos");
            }
        }
コード例 #6
0
        public static bool Guardar(Ciudades ciudad)
        {
            bool     paso = false;
            Contexto db   = new Contexto();

            try
            {
                if (db.Ciudades.Add(ciudad) != null)
                {
                    paso = db.SaveChanges() > 0;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                db.Dispose();
            }
            return(paso);
        }
コード例 #7
0
ファイル: frmCiudades.cs プロジェクト: alexbeltrang/SIVEDI
 private void btnGrabar_Click(object sender, EventArgs e)
 {
     if (validaCampos())
     {
         string   strResultado;
         Ciudades ciudades = new Ciudades();
         ServicioGeneralClient servicioGeneral = new ServicioGeneralClient();
         if (rbnActivo.Checked)
         {
             ciudades.ESTADO = true;
         }
         else if (rbnInactivo.Checked)
         {
             ciudades.ESTADO = false;
         }
         ciudades.CODIGO              = intCodigoCiudad;
         ciudades.NOMBRE              = txtNombreCiudad.Text.ToUpper();
         ciudades.CODIGO_DANE         = txtCodigoDaneCiudad.Text.ToUpper();
         ciudades.CODIGO_DEPARTAMENTO = Convert.ToInt32(cboDepto.SelectedValue);
         strResultado = Convert.ToString(servicioGeneral.insCiudades(ciudades));
         if (Information.IsNumeric(strResultado))
         {
             llenaGrilla(Convert.ToInt32(cboDepto.SelectedValue));
             limpiaCampos();
             if (Convert.ToInt32(strResultado) == 1)
             {
                 MessageBox.Show("Registro creado exitosamente", "Registro", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
             }
             else if (Convert.ToInt32(strResultado) == 2)
             {
                 MessageBox.Show("Registro Actualizado exitosamente", "Actualización", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
             }
         }
         else
         {
             MessageBox.Show("Error al grabar en la Base de Datos, contacte al Administrador del Sistema", "Error BD", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
         }
     }
 }
コード例 #8
0
        private void BotonBuscar_Click(object sender, EventArgs e)
        {
            int id;

            Ciudades ciudades = new Ciudades();

            int.TryParse(NumericUpDown.Text, out id);

            Limpiar();

            ciudades = CiudadBLL.Buscar(id);

            if (ciudades != null)
            {
                MessageBox.Show("Ciudad encontrada");
                LlenarCampo(ciudades);
            }
            else
            {
                MessageBox.Show("Ciudad no esta en base de datos");
            }
        }
コード例 #9
0
        protected void GuadarButton_Click(object sender, EventArgs e)
        {
            BLL.RepositorioBase <Ciudades> repositorio = new BLL.RepositorioBase <Ciudades>();
            Ciudades ciudades = new Ciudades();
            bool     paso     = false;

            LlenaClase(ciudades);

            if (IsValid)
            {
                if (ciudades.CiudadId == 0)
                {
                    if (paso = repositorio.Guardar(ciudades))
                    {
                        Utils.ShowToastr(this, "saved successfully", "Success", "success");
                        Limpiar();
                    }
                    else
                    {
                        Utils.ShowToastr(this, "ERROR AL GUARDAR ", "Error", "error");
                        Limpiar();
                    }
                }

                else
                {
                    if (repositorio.Modificar(LlenaClase(ciudades)))
                    {
                        Utils.ShowToastr(this, "Modificado ", "Info", "info");
                        Limpiar();
                    }
                    else
                    {
                        Utils.ShowToastr(this, "ERROR AL MODIFICAR ", "Error", "error");
                    }
                }
            }
        }
コード例 #10
0
        public void DepartmentChange()
        {
            SelectedCiudad = null;

            Ciudades.Clear();


            Ciudad_Id  = -1;
            Empresa_Id = -1;
            // VisibleRadioButtonDetallado=false;
            ReportType         = "General";
            IsVisibleExportPdf = false;


            if (SelectedDeparment != null)
            {
                Departamento_Id = SelectedDeparment.Id;
                Ciudades        = GetQueryableCiudades(Departamento_Id).Result.ToList();
                Ciudades.Add(new Ciudad {
                    Id     = 0,
                    Nombre = "Todos los municipios",
                });
            }
            else
            {
                Ciudad_Id       = -1;
                Empresa_Id      = -1;
                Departamento_Id = -1;
                /// VisibleRadioButtonDetallado=false;
                ReportType = "General";
            }


            Limpiar = true;
            InitElementos();

            /// InitElementos();
        }
コード例 #11
0
        public static IEnumerable <SelectListItem> GetCiudades(long IdPais, long IdEstado)
        {
            List <SelectListItem> Ciudades;

            using (SeguricelEntities db = new SeguricelEntities())
            {
                Ciudades = (from c in db.Pais_Estado_Ciudad
                            where c.IdPais == IdPais && c.IdEstado == IdEstado
                            select new SelectListItem
                {
                    Value = c.IdCiudad.ToString(),
                    Text = c.Nombre
                }).ToList();
            }

            Ciudades.Insert(0, new SelectListItem
            {
                Value = "0",
                Text  = Resources.EtiquetasResource.labelSelectValue
            });

            return(Ciudades.ToList());
        }
コード例 #12
0
        public async Task <Ciudades> CiudadesGetById(int Id)
        {
            using (SqlConnection sql = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SP_SEL_Ciudades_ById", sql))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("@IdCiudad", Id));
                    Ciudades response = null;
                    await sql.OpenAsync();

                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            response = MapToCiudades(reader);
                        }
                    }

                    return(response);
                }
            }
        }
コード例 #13
0
        private void EliminarButton_Click(object sender, EventArgs e)
        {
            Ciudades ciudad = new Ciudades();

            if (CiudadIdTextBox.TextLength == 0)
            {
                MessageBox.Show("Debe especificar el ID", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            if (CiudadIdTextBox.Text.Length > 0)
            {
                ciudad.CiudadId = Convertir();
                if (ciudad.Eliminar())
                {
                    MessageBox.Show("Ciudad Eliminada correctamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    NuevoButton.PerformClick();
                }
                else
                {
                    MessageBox.Show("Error al eliminar la ciudad", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
コード例 #14
0
 private void actualizarTabla()
 {
     dgvViajesDisponibles.Rows.Clear();
     dgvViajesDisponibles.Refresh();
     if (cmbOrigen.Text == "" || cmbDestino.Text == "")
     {
     }
     else
     {
         int    origen  = Ciudades.obtenerID(cmbOrigen.Text);
         int    destino = Ciudades.obtenerID(cmbDestino.Text);
         string query   = "SELECT * FROM JUST_DO_IT.vuelosDisponibles(" + origen + ", " + destino + ", '" +
                          dtpFechaSalidaVuelo.Value.ToString("yyyy-MM-dd") + "')";
         SqlDataReader reader = Server.getInstance().query(query);
         while (reader.Read())
         {
             dgvViajesDisponibles.Rows.Add(reader["vuelo"].ToString(), reader["cantidad"].ToString(),
                                           reader["kgsDisponibles"].ToString(), reader["salida"].ToString(), reader["llegada"].ToString(),
                                           reader["tipoServicio"].ToString(),
                                           reader["costoViaje"].ToString(), reader["costoEncomienda"].ToString());
         }
         reader.Close();
     }
 }
コード例 #15
0
        private void cargarDatos()
        {
            if (!(cmbDestino.Text == "" || cmbOrigen.Text == ""))
            {
                cmbRutas.Items.Clear();
                int           origen    = Ciudades.obtenerID(cmbOrigen.Text);
                int           destino   = Ciudades.obtenerID(cmbDestino.Text);
                List <string> codigos   = new List <string>();
                List <int>    servicios = new List <int>();
                List <double> ids       = new List <double>();
                string        query     = "SELECT id, codigo, tipo_servicio, eliminada FROM JUST_DO_IT.Rutas WHERE ciu_id_origen=" + origen + " AND ciu_id_destino=" + destino;
                SqlDataReader reader    = Server.getInstance().query(query);
                while (reader.Read())
                {
                    string al = reader["eliminada"].ToString();

                    if (reader["eliminada"].ToString() == "False")
                    {
                        codigos.Add(reader["codigo"].ToString());
                        servicios.Add(int.Parse(reader["tipo_servicio"].ToString()));
                        ids.Add(double.Parse(reader["id"].ToString()));
                    }
                }
                reader.Close();
                int          i;
                ComboBoxItem item = new ComboBoxItem(cmbRutas);
                for (i = 0; i < codigos.Count; i++)
                {
                    string servicio = TiposServicios.obtenerNombre(servicios.ElementAt(i));
                    item       = new ComboBoxItem();
                    item.Value = ids.ElementAt(i);
                    item.Text  = codigos.ElementAt(i) + " - " + servicio;
                    cmbRutas.Items.Add(item);
                }
            }
        }
コード例 #16
0
 //private AzureService _service = new AzureService();
 public DetailViewModel(Ciudades ciudad)
 {
     CiudadSeleccionada = ciudad;
 }
コード例 #17
0
            public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs)
            {
                global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
                global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
                Ciudades ds = new Ciudades();

                global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
                any1.Namespace       = "http://www.w3.org/2001/XMLSchema";
                any1.MinOccurs       = new decimal(0);
                any1.MaxOccurs       = decimal.MaxValue;
                any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any1);
                global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
                any2.Namespace       = "urn:schemas-microsoft-com:xml-diffgram-v1";
                any2.MinOccurs       = new decimal(1);
                any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute1.Name       = "namespace";
                attribute1.FixedValue = ds.Namespace;
                type.Attributes.Add(attribute1);
                global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute2.Name       = "tableTypeName";
                attribute2.FixedValue = "CIUDADESDataTable";
                type.Attributes.Add(attribute2);
                type.Particle = sequence;
                global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
                if (xs.Contains(dsSchema.TargetNamespace))
                {
                    global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                    global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                    try {
                        global::System.Xml.Schema.XmlSchema schema = null;
                        dsSchema.Write(s1);
                        for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                        {
                            schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                            s2.SetLength(0);
                            schema.Write(s2);
                            if ((s1.Length == s2.Length))
                            {
                                s1.Position = 0;
                                s2.Position = 0;
                                for (; ((s1.Position != s1.Length) &&
                                        (s1.ReadByte() == s2.ReadByte()));)
                                {
                                    ;
                                }
                                if ((s1.Position == s1.Length))
                                {
                                    return(type);
                                }
                            }
                        }
                    }
                    finally {
                        if ((s1 != null))
                        {
                            s1.Close();
                        }
                        if ((s2 != null))
                        {
                            s2.Close();
                        }
                    }
                }
                xs.Add(dsSchema);
                return(type);
            }
コード例 #18
0
        public void ImportarCSV(int Tipo, FileStream file, string ruta)
        {
            file.Position = 0;

            var reader = new StreamReader(file);

            WebClient webClient = new WebClient();

            /*
             * Tipos
             * 1 - Ciudad
             * 2 - Comida
             * 3 - Tipo de Atraccion
             * 4 - Atraccion
             * */
            string                  headers;
            CiudadesRepository      ciudadesRepository;
            ComidasRepository       comidasRepository;
            TipoAtraccionRepository tipoAtraccionRepository;
            AtraccionesRepository   atraccionesRepository;

            switch (Tipo)
            {
            case 1:
                headers = reader.ReadLine();
                if (headers != "Nombre,Portada,Contenido")
                {
                    throw new Exception("El orden de las columnas no es el correcto [ Nombre,Portada,Contenido ] (La portada debe ser un link de una imagen JPG)");
                }

                ciudadesRepository = new CiudadesRepository();

                Context.Database.BeginTransaction();

                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split(',');

                    if (ciudadesRepository.GetCiudadesByNombre(values[0]) == null)
                    {
                        Ciudades ciudades = new Ciudades()
                        {
                            Nombre    = values[0],
                            Contenido = values[2]
                        };

                        Context.Add(ciudades);
                        Context.SaveChanges();

                        webClient.DownloadFile(values[1], $"{ruta}/images/ciudades/{ciudades.Id}.jpg");
                    }
                    else
                    {
                        throw new Exception($"Ya existe una ciudad con el nombre de [ {values[0]} ]");
                    }
                }

                Context.Database.CommitTransaction();
                break;

            case 2:
                headers = reader.ReadLine();
                if (headers != "Nombre,Portada,Descripcion,Ciudad")
                {
                    throw new Exception("El orden de las columnas no es el correcto [ Nombre,Portada,Descripcion,Ciudad ] (La portada debe ser un link de una imagen JPG)");
                }

                ciudadesRepository = new CiudadesRepository();
                comidasRepository  = new ComidasRepository();

                Context.Database.BeginTransaction();

                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split(',');
                    var ciudad = ciudadesRepository.GetCiudadesByNombre(values[3]);

                    if (comidasRepository.GetComidaByNombre(values[0]) == null)
                    {
                        if (ciudad == null)
                        {
                            throw new Exception($"No existe una ciudad con el nombre de [ {values[3]} ]");
                        }

                        Comidas comidas = new Comidas()
                        {
                            Nombre      = values[0],
                            Descripcion = values[2],
                            IdCiudad    = ciudad.Id
                        };

                        Context.Add(comidas);
                        Context.SaveChanges();

                        webClient.DownloadFile(values[1], $"{ruta}/images/comidas/{comidas.Id}.jpg");
                    }
                    else
                    {
                        throw new Exception($"Ya existe una comida con el nombre de [ {values[0]} ]");
                    }
                }

                Context.Database.CommitTransaction();
                break;

            case 3:
                headers = reader.ReadLine();
                if (headers != "Tipo,Icono")
                {
                    throw new Exception("El orden de las columnas no es el correcto [ Tipo,Icono ] (El icono debe ser un link de una imagen JPG)");
                }

                tipoAtraccionRepository = new TipoAtraccionRepository();

                Context.Database.BeginTransaction();

                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split(',');

                    if (tipoAtraccionRepository.GetTipoAtraccionByTipo(values[0]) == null)
                    {
                        Tipoatraccion tipoatraccion = new Tipoatraccion()
                        {
                            Tipo = values[0]
                        };

                        Context.Add(tipoatraccion);
                        Context.SaveChanges();

                        webClient.DownloadFile(values[1], $"{ruta}/images/tipoatraccion/{tipoatraccion.Id}.jpg");
                    }
                    else
                    {
                        throw new Exception($"Ya existe este tipo de atraccion con el nombre de [ {values[0]} ]");
                    }
                }

                Context.Database.CommitTransaction();
                break;

            case 4:
                headers = reader.ReadLine();
                if (headers != "Titulo,Portada,Contenido,Ciudad,Tipo")
                {
                    throw new Exception("El orden de las columnas no es el correcto [ Titulo,Portada,Contenido,Ciudad,Tipo ] (La portada debe ser un link de una imagen JPG)");
                }

                atraccionesRepository   = new AtraccionesRepository();
                ciudadesRepository      = new CiudadesRepository();
                tipoAtraccionRepository = new TipoAtraccionRepository();

                Context.Database.BeginTransaction();

                while (!reader.EndOfStream)
                {
                    var line          = reader.ReadLine();
                    var values        = line.Split(',');
                    var ciudad        = ciudadesRepository.GetCiudadesByNombre(values[3]);
                    var tipoatraccion = tipoAtraccionRepository.GetTipoAtraccionByTipo(values[4]);

                    if (atraccionesRepository.GetAtraccionesByTitulo(values[0]) == null)
                    {
                        if (ciudad == null)
                        {
                            throw new Exception($"No existe una ciudad con el nombre de [ {values[3]} ]");
                        }

                        if (tipoatraccion == null)
                        {
                            throw new Exception($"No existe un tipo de atraccion con el nombre de [ {values[4]} ]");
                        }

                        Atracciones atracciones = new Atracciones()
                        {
                            Titulo    = values[0],
                            Contenido = values[2],
                            IdCiudad  = ciudad.Id,
                            IdTipo    = tipoatraccion.Id
                        };

                        Context.Add(atracciones);
                        Context.SaveChanges();

                        webClient.DownloadFile(values[1], $"{ruta}/images/atracciones/{atracciones.Id}.jpg");
                    }
                    else
                    {
                        throw new Exception($"Ya existe una atraccion con el titulo de [ {values[0]} ]");
                    }
                }

                Context.Database.CommitTransaction();
                break;

            default:
                throw new Exception("Seleccione un tipo de registro valido");
            }
        }
コード例 #19
0
        public void ImportarExcel(int Tipo, FileStream file, string ruta)
        {
            file.Position = 0;

            IWorkbook workbook = new XSSFWorkbook(file);
            ISheet    sheet    = workbook.GetSheetAt(0);

            var primerRow = sheet.GetRow(0);

            /*
             * Tipos
             * 1 - Ciudad
             * 2 - Comida
             * 3 - Tipo de Atraccion
             * 4 - Atraccion
             * */

            switch (Tipo)
            {
            case 1:
                if (primerRow.GetCell(0).StringCellValue == "Nombre" &&
                    primerRow.GetCell(1).StringCellValue == "Portada" &&
                    primerRow.GetCell(2).StringCellValue == "Contenido")
                {
                    int lastRow = sheet.LastRowNum;
                    CiudadesRepository ciudadesRepository = new CiudadesRepository();

                    Context.Database.BeginTransaction();

                    WebClient webClient = new WebClient();

                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        if (ciudadesRepository.GetCiudadesByNombre(sheet.GetRow(i).GetCell(0).StringCellValue) == null)
                        {
                            Ciudades ciudades = new Ciudades()
                            {
                                Nombre    = sheet.GetRow(i).GetCell(0).StringCellValue,
                                Contenido = sheet.GetRow(i).GetCell(2).StringCellValue
                            };

                            Context.Add(ciudades);
                            Context.SaveChanges();

                            webClient.DownloadFile(sheet.GetRow(i).GetCell(1).StringCellValue, $"{ruta}/images/ciudades/{ciudades.Id}.jpg");
                        }
                        else
                        {
                            throw new Exception($"Ya existe una ciudad con el nombre de [ {sheet.GetRow(i).GetCell(0).StringCellValue} ]");
                        }
                    }
                    Context.Database.CommitTransaction();
                }
                else
                {
                    workbook.Close();
                    throw new Exception("El archivo de Excel no tiene los datos en el orden correcto [ Nombre,Portada,Contenido ] (La portada debe ser un link de una imagen JPG)");
                }
                break;

            case 2:
                if (primerRow.GetCell(0).StringCellValue == "Nombre" &&
                    primerRow.GetCell(1).StringCellValue == "Portada" &&
                    primerRow.GetCell(2).StringCellValue == "Descripcion" &&
                    primerRow.GetCell(3).StringCellValue == "Ciudad")
                {
                    int lastRow = sheet.LastRowNum;
                    CiudadesRepository ciudadesRepository = new CiudadesRepository();
                    ComidasRepository  comidasRepository  = new ComidasRepository();

                    Context.Database.BeginTransaction();

                    WebClient webClient = new WebClient();

                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        if (comidasRepository.GetComidaByNombre(sheet.GetRow(i).GetCell(0).StringCellValue) == null)
                        {
                            Ciudades ciudad = ciudadesRepository.GetCiudadesByNombre(sheet.GetRow(i).GetCell(3).StringCellValue);

                            if (ciudad == null)
                            {
                                throw new Exception($"No existe una ciudad con el nombre de [ {sheet.GetRow(i).GetCell(3).StringCellValue} ]");
                            }

                            Comidas comidas = new Comidas()
                            {
                                Nombre      = sheet.GetRow(i).GetCell(0).StringCellValue,
                                Descripcion = sheet.GetRow(i).GetCell(2).StringCellValue,
                                IdCiudad    = ciudad.Id
                            };

                            Context.Add(comidas);
                            Context.SaveChanges();

                            webClient.DownloadFile(sheet.GetRow(i).GetCell(1).StringCellValue, $"{ruta}/images/comidas/{comidas.Id}.jpg");
                        }
                        else
                        {
                            throw new Exception($"Ya existe una comida con el nombre de [ {sheet.GetRow(i).GetCell(0).StringCellValue} ]");
                        }
                    }
                    Context.Database.CommitTransaction();
                }
                else
                {
                    workbook.Close();
                    throw new Exception("El archivo de Excel no tiene los datos en el orden correcto [ Nombre,Portada,Descripcion,Ciudad ] (La portada debe ser un link de una imagen JPG)");
                }
                break;

            case 3:
                if (primerRow.GetCell(0).StringCellValue == "Tipo" &&
                    primerRow.GetCell(1).StringCellValue == "Icono")
                {
                    int lastRow = sheet.LastRowNum;
                    TipoAtraccionRepository tipoAtraccionRepository = new TipoAtraccionRepository();

                    Context.Database.BeginTransaction();

                    WebClient webClient = new WebClient();

                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        if (tipoAtraccionRepository.GetTipoAtraccionByTipo(sheet.GetRow(i).GetCell(0).StringCellValue) == null)
                        {
                            Tipoatraccion tipoatraccion = new Tipoatraccion()
                            {
                                Tipo = sheet.GetRow(i).GetCell(0).StringCellValue
                            };

                            Context.Add(tipoatraccion);
                            Context.SaveChanges();

                            webClient.DownloadFile(sheet.GetRow(i).GetCell(1).StringCellValue, $"{ruta}/images/tipoatraccion/{tipoatraccion.Id}.jpg");
                        }
                        else
                        {
                            throw new Exception($"Ya existe este tipo de atraccion con el nombre de [ {sheet.GetRow(i).GetCell(0).StringCellValue} ]");
                        }
                    }
                    Context.Database.CommitTransaction();
                }
                else
                {
                    workbook.Close();
                    throw new Exception("El archivo de Excel no tiene los datos en el orden correcto [ Tipo,Icono ] (El icono debe ser un link de una imagen JPG)");
                }
                break;

            case 4:
                if (primerRow.GetCell(0).StringCellValue == "Titulo" &&
                    primerRow.GetCell(1).StringCellValue == "Portada" &&
                    primerRow.GetCell(2).StringCellValue == "Contenido" &&
                    primerRow.GetCell(3).StringCellValue == "Ciudad" &&
                    primerRow.GetCell(4).StringCellValue == "Tipo")
                {
                    int lastRow = sheet.LastRowNum;
                    AtraccionesRepository   atraccionesRepository   = new AtraccionesRepository();
                    CiudadesRepository      ciudadesRepository      = new CiudadesRepository();
                    TipoAtraccionRepository tipoAtraccionRepository = new TipoAtraccionRepository();

                    Context.Database.BeginTransaction();

                    WebClient webClient = new WebClient();

                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        if (atraccionesRepository.GetAtraccionesByTitulo(sheet.GetRow(i).GetCell(0).StringCellValue) == null)
                        {
                            Ciudades ciudad = ciudadesRepository.GetCiudadesByNombre(sheet.GetRow(i).GetCell(3).StringCellValue);

                            if (ciudad == null)
                            {
                                throw new Exception($"No existe una ciudad con el nombre de [ {sheet.GetRow(i).GetCell(3).StringCellValue} ]");
                            }

                            Tipoatraccion tipoatraccion = tipoAtraccionRepository.GetTipoAtraccionByTipo(sheet.GetRow(i).GetCell(4).StringCellValue);

                            if (tipoatraccion == null)
                            {
                                throw new Exception($"No existe un tipo de atraccion con el nombre de [ {sheet.GetRow(i).GetCell(4).StringCellValue} ]");
                            }

                            Atracciones atracciones = new Atracciones()
                            {
                                Titulo    = sheet.GetRow(i).GetCell(0).StringCellValue,
                                Contenido = sheet.GetRow(i).GetCell(2).StringCellValue,
                                IdCiudad  = ciudad.Id,
                                IdTipo    = tipoatraccion.Id
                            };

                            Context.Add(atracciones);
                            Context.SaveChanges();

                            webClient.DownloadFile(sheet.GetRow(i).GetCell(1).StringCellValue, $"{ruta}/images/atracciones/{atracciones.Id}.jpg");
                        }
                        else
                        {
                            throw new Exception($"Ya existe una atraccion con el titulo de [ {sheet.GetRow(i).GetCell(0).StringCellValue} ]");
                        }
                    }
                    Context.Database.CommitTransaction();
                }
                else
                {
                    workbook.Close();
                    throw new Exception("El archivo de Excel no tiene los datos en el orden correcto [ Titulo,Portada,Contenido,Ciudad,Tipo ] (La portada debe ser un link de una imagen JPG)");
                }
                break;

            default:
                throw new Exception("Seleccione un tipo de registro valido");
            }
        }
コード例 #20
0
        private bool ExisteEnLaBaseDeDatos()
        {
            Ciudades ciudad = CiudadesBLL.Buscar((int)IdNumericUpDown1.Value);

            return(ciudad != null);
        }
コード例 #21
0
        public string InsertarCiudad(out int id_ciudad, Ciudades ciudad)
        {
            id_ciudad = 0;
            int    contador = 0;
            string rpta     = "";

            string consulta = "INSERT INTO Ciudades (Id_pais, Nombre_ciudad, Observaciones_ciudad, Estado_ciudad) " +
                              "VALUES(@Id_pais, @Nombre_ciudad, @Observaciones_ciudad, @Estado_ciudad) " +
                              "SET @Id_ciudad = SCOPE_IDENTITY() ";

            SqlConnection SqlCon = new SqlConnection();

            SqlCon.InfoMessage += new SqlInfoMessageEventHandler(SqlCon_InfoMessage);
            SqlCon.FireInfoMessageEventOnUserErrors = true;
            try
            {
                SqlCon.ConnectionString = DConexion.Cn;
                SqlCon.Open();
                SqlCommand SqlCmd = new SqlCommand
                {
                    Connection  = SqlCon,
                    CommandText = consulta,
                    CommandType = CommandType.Text
                };

                SqlParameter Id_ciudad = new SqlParameter
                {
                    ParameterName = "@Id_ciudad",
                    SqlDbType     = SqlDbType.Int,
                    Direction     = ParameterDirection.Output
                };
                SqlCmd.Parameters.Add(Id_ciudad);

                SqlParameter Id_pais = new SqlParameter
                {
                    ParameterName = "@Id_pais",
                    SqlDbType     = SqlDbType.Int,
                    Value         = ciudad.Id_pais
                };
                SqlCmd.Parameters.Add(Id_pais);
                contador += 1;

                SqlParameter Nombre_ciudad = new SqlParameter
                {
                    ParameterName = "@Nombre_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Nombre_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Nombre_ciudad);
                contador += 1;

                SqlParameter Observaciones_ciudad = new SqlParameter
                {
                    ParameterName = "@Observaciones_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Observaciones_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Observaciones_ciudad);
                contador += 1;

                SqlParameter Estado_ciudad = new SqlParameter
                {
                    ParameterName = "@Estado_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Estado_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Estado_ciudad);
                contador += 1;

                //Ejecutamos nuestro comando
                rpta = SqlCmd.ExecuteNonQuery() >= 1 ? "OK" : "NO SE INGRESÓ";
                if (!rpta.Equals("OK"))
                {
                    if (this.Mensaje_respuesta != null)
                    {
                        rpta = this.Mensaje_respuesta;
                    }
                }
                else
                {
                    id_ciudad = Convert.ToInt32(SqlCmd.Parameters["@Id_ciudad"].Value);
                }
            }
            //Mostramos posible error que tengamos
            catch (SqlException ex)
            {
                rpta = ex.Message;
            }
            catch (Exception ex)
            {
                rpta = ex.Message;
            }
            finally
            {
                //Si la cadena SqlCon esta abierta la cerramos
                if (SqlCon.State == ConnectionState.Open)
                {
                    SqlCon.Close();
                }
            }
            return(rpta);
        }
コード例 #22
0
        public string EditarCiudad(int id_ciudad, Ciudades ciudad)
        {
            int    contador = 0;
            string rpta     = "";

            string consulta = "UPDATE Ciudades SET " +
                              "Id_pais = @Id_pais, " +
                              "Nombre_ciudad = @Nombre_ciudad, " +
                              "Observaciones_ciudad = @Observaciones_ciudad, " +
                              "Estado_ciudad = @Estado_ciudad " +
                              "WHERE Id_ciudad = @Id_ciudad ";

            SqlConnection SqlCon = new SqlConnection();

            SqlCon.InfoMessage += new SqlInfoMessageEventHandler(SqlCon_InfoMessage);
            SqlCon.FireInfoMessageEventOnUserErrors = true;
            try
            {
                SqlCon.ConnectionString = DConexion.Cn;
                SqlCon.Open();
                SqlCommand SqlCmd = new SqlCommand
                {
                    Connection  = SqlCon,
                    CommandText = consulta,
                    CommandType = CommandType.Text
                };

                SqlParameter Id_ciudad = new SqlParameter
                {
                    ParameterName = "@Id_ciudad",
                    SqlDbType     = SqlDbType.Int,
                    Value         = id_ciudad,
                };
                SqlCmd.Parameters.Add(Id_ciudad);

                SqlParameter Id_pais = new SqlParameter
                {
                    ParameterName = "@Id_pais",
                    SqlDbType     = SqlDbType.Int,
                    Value         = ciudad.Id_pais
                };
                SqlCmd.Parameters.Add(Id_pais);
                contador += 1;

                SqlParameter Nombre_ciudad = new SqlParameter
                {
                    ParameterName = "@Nombre_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Nombre_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Nombre_ciudad);
                contador += 1;

                SqlParameter Observaciones_ciudad = new SqlParameter
                {
                    ParameterName = "@Observaciones_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Observaciones_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Observaciones_ciudad);
                contador += 1;

                SqlParameter Estado_ciudad = new SqlParameter
                {
                    ParameterName = "@Estado_ciudad",
                    SqlDbType     = SqlDbType.VarChar,
                    Size          = 50,
                    Value         = ciudad.Estado_ciudad.Trim()
                };
                SqlCmd.Parameters.Add(Estado_ciudad);
                contador += 1;

                //Ejecutamos nuestro comando
                rpta = SqlCmd.ExecuteNonQuery() >= 1 ? "OK" : "NO SE INGRESÓ";
                if (!rpta.Equals("OK"))
                {
                    if (this.Mensaje_respuesta != null)
                    {
                        rpta = this.Mensaje_respuesta;
                    }
                }
            }
            //Mostramos posible error que tengamos
            catch (SqlException ex)
            {
                rpta = ex.Message;
            }
            catch (Exception ex)
            {
                rpta = ex.Message;
            }
            finally
            {
                //Si la cadena SqlCon esta abierta la cerramos
                if (SqlCon.State == ConnectionState.Open)
                {
                    SqlCon.Close();
                }
            }
            return(rpta);
        }
コード例 #23
0
 private void Limpiar()
 {
     this.ciudades    = new Ciudades();
     this.DataContext = ciudades;
 }
コード例 #24
0
 private void LlenaCampos(Ciudades ciudades)
 {
     NombreTextBox.Text = ciudades.Nombres;
 }
コード例 #25
0
 public rCiudades()
 {
     InitializeComponent();
     ciudad = new Ciudades();
 }
コード例 #26
0
        public async Task <ActionResult <Respuesta> > PostCiudades([FromBody] CiudadRequest ciudadRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Respuesta
                {
                    EsExitoso = false,
                    Mensaje = "Modelo incorrecto.",
                    Resultado = ModelState
                }));
            }

            var user = await this.context.Users.FindAsync("1");

            if (user == null)
            {
                return(BadRequest(new Respuesta
                {
                    EsExitoso = false,
                    Mensaje = "Usuario Invalido.",
                    Resultado = null
                }));
            }

            var provincia = await this.context.Provincias.FindAsync(ciudadRequest.ProvinciaId);

            if (provincia == null)
            {
                return(BadRequest(new Respuesta
                {
                    EsExitoso = false,
                    Mensaje = "Provincia no existe.",
                    Resultado = null
                }));
            }

            var entity = new Ciudades
            {
                NombreCiudad = ciudadRequest.NombreCiudad,
                Provincia    = provincia,
                Usuario      = user,
            };

            BaseController.CompletaRegistro(entity, 1, "", user, false);

            await this.context.Set <Ciudades>().AddAsync(entity);

            try
            {
                await this.context.SaveChangesAsync();
            }
            catch (Exception ee)
            {
                return(BadRequest(new Respuesta
                {
                    EsExitoso = false,
                    Mensaje = "Registro no grabado, controlar.",
                    Resultado = null
                }));
            }

            return(Ok(new Respuesta
            {
                EsExitoso = true,
                Mensaje = "",
                Resultado = new CiudadRespuesta
                {
                    CiudadId = entity.Id,
                    ProvinciaId = entity.ProvinciaId,
                    NombreCiudad = entity.NombreCiudad,
                    NombreProvincia = entity.Provincia.NombreProvincia
                }
            }));
        }
コード例 #27
0
 private void LlenaCampo(Ciudades ciudad)
 {
     IdNumericUpDown1.Value = ciudad.CiudadId;
     NombreTextBox.Text     = ciudad.Nombre;
 }
コード例 #28
0
        public Ciudades LlenaClase(Ciudades ciudades)
        {
            ciudades.Nombres = NombreTextBox.Text;

            return(ciudades);
        }
コード例 #29
0
 public void AsignarCiudad(int adminID, Ciudades c)
 {
     _dala.AsignarCiudad(adminID, c);
 }
コード例 #30
0
 public async Task borrarCiudadAsync(Ciudades ciudad)
 {
     await _table.DeleteAsync(ciudad);
 }