Exemplo n.º 1
0
        public void importarExcelFuncional(ToolStripProgressBar bar)
        {
            try
            {
                bar.Visible = true;
                OpenFileDialog fichero = new OpenFileDialog();
                fichero.Filter = "Excel (*.xls)|*.xls;*.xlsx";
                //ArrayList lstDatos = new ArrayList(); ;

                stratum = new ESTRATO();

                ProjectBL pyBl = new ProjectBL(Program.ContextData);
                FormBL formBl = new FormBL(Program.ContextData);
                InventoryLineBL lineInvBl = new InventoryLineBL(Program.ContextData);
                listStratumsAdded = new ArrayList();

                USUARIO user = (USUARIO)Program.Cache.Get("user");

                if (user != null)
                {
                    try
                    {
                        if (fichero.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            //PROYECTO project;
                            //PROYECTO py = pyBl.GetProject(project.NROPROY);
                            bar.Visible = true;
                            bar.Value = 0;

                            //declaramos las variables que necesitamos para poder abrir un archivo excel
                            excel.Application aplicacion;
                            excel.Workbook libros_trabajo;
                            excel.Worksheet hojas_trabajo;
                            excel.Range exlRange;

                            aplicacion = new excel.Application();

                            //Asignamos el libro que sera abierot
                            libros_trabajo = aplicacion.Workbooks.Open(fichero.FileName, 0, true, 5, "", "", true, excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

                            hojas_trabajo = (excel.Worksheet)libros_trabajo.Worksheets.get_Item(3);
                            exlRange = hojas_trabajo.UsedRange;
                            //Recorremos el archivo excel como si fuera una matriz
                            //leemos los proyectos que se encuentran en la hoja
                            bar.Maximum = exlRange.Rows.Count - 2;

                            for (int i = 2; i <= exlRange.Rows.Count; i++)
                            {

                                string lugar = "" + (exlRange.Cells[i, 1] as excel.Range).Value + "";
                                string tamanioParcela = "" + (exlRange.Cells[i, 2] as excel.Range).Value + "";
                                string tamanioSupTotal = "" + (exlRange.Cells[i, 3] as excel.Range).Value + "";
                                string areaderegeneracion = "" + (exlRange.Cells[i, 4] as excel.Range).Value + "";
                                string factorForma = "" + (exlRange.Cells[i, 5] as excel.Range).Value + "";
                                //string numeroEtapas = "" + (exlRange.Cells[i, 6] as excel.Range).Value + "";
                                string descripcion = "" + (exlRange.Cells[i, 7] as excel.Range).Value + "";
                                string TipoDisenio = "" + (exlRange.Cells[i, 8] as excel.Range).Value + "";
                                string Objetivo = "" + (exlRange.Cells[i, 9] as excel.Range).Value + "";
                                string confianza = "" + (exlRange.Cells[i, 10] as excel.Range).Value + "";
                                if (pyBl.GetProjectByPlace(lugar) == null)
                                {
                                    // area muestreada = multiplicar el numero de parcelas por el tamaño de la parcela
                                    // intensidad de muestreo = dividir el area muestreada entre el tamaño total del area a muestrear
                                    PROYECTO py = new PROYECTO();
                                    py.NROPROY = Guid.NewGuid();
                                    py.LUGAR = lugar;
                                    decimal tam = 0, factor = 0, tamSupTotal = 0, conf = 0;
                                    int areaReg = 0;
                                    decimal.TryParse(tamanioParcela.Replace(".", ","), out tam);
                                    py.TAMANO = tam;
                                    decimal.TryParse(tamanioSupTotal.Replace(".", ","), out tamSupTotal);
                                    py.SUPTOT = tamSupTotal;
                                    int.TryParse(areaderegeneracion, out areaReg);
                                    py.AREAFUSTALESPORPARCELA = areaReg;
                                    decimal.TryParse(factorForma.Replace(".", ","), out factor);
                                    py.FACTORDEFORMA = factor;
                                    py.ETAPA = 0;
                                    py.DESCRIPCION = descripcion;
                                    decimal.TryParse(confianza.Replace(".", ","), out conf);
                                    py.CONFIANZA = conf;
                                    TypeSampleDesignBl desingType = new TypeSampleDesignBl(Program.ContextData);
                                    ObjectiveInventoryBL objInvBl = new ObjectiveInventoryBL(Program.ContextData);
                                    if (TipoDisenio.Equals("Estratificado")) py.NOMTIPODISEMUEST = "ES";
                                    else if (TipoDisenio.Equals("Simple")) py.NOMTIPODISEMUEST = "SI";
                                    if (Objetivo.Equals("Maderable")) py.NOMBRETIPOINV = "MD";
                                    else if (Objetivo.Equals("No Maderable")) py.NOMBRETIPOINV = "NM";
                                    py.FECHA = DateTime.Now;
                                    py.TIPOPROYECTO = "CR";
                                    py.NROFORMULA = Guid.Parse("ED52569E-5CFD-454F-9F8B-9429A47C829F");
                                    py.SUPMUE = 0;
                                    py.INTMUE = 0;
                                    py.LIMITINFDAP = 10;
                                    py.USUARIO = user;
                                    py.NROUSUARIO = user.NROUSUARIO;
                                    pyBl.InsertProject(py);
                                    string result = pyBl.SaveChanges();

                                    if (!result.Equals(""))
                                    {
                                        Error_Form errorForm = new Error_Form(result);
                                        ToolStrip menu = bar.GetCurrentParent();
                                        Principal_Form parent = (Principal_Form)menu.Parent;
                                        errorForm.MdiParent = (Form)parent;
                                        errorForm.Show();
                                        return;
                                    }
                                    bar.Increment(1);
                                }

                            }

                            exlRange = hojas_trabajo.UsedRange;

                            this.loadSpecies(bar, 2);

                            //recorremos el archivo para leer las lineas de inventario que estan en el libro
                            hojas_trabajo = (excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);

                            //Definimos el el rango de celdas que seran leidas
                            exlRange = hojas_trabajo.UsedRange;

                            int posStratum = 0, posBloque = 0, posNomCom = 0, posFam = 0, posNomCien = 0, posParcela = 0, posCodCal = 0, posNumArb = 0;
                            //Recorremos el archivo excel como si fuera una matriz
                            string sValor = "";
                            posBloque = 1;
                            posStratum = 2;
                            posParcela = 3;
                            posNumArb = 4;
                            posNomCom = 5;
                            posNomCien = 6;
                            posFam = 7;
                            posCodCal = 11;
                            sValor = "" + (exlRange.Cells[3, posParcela] as excel.Range).Value + "";
                            int Numparcera = int.Parse(sValor); // se obtiene el numero de la parcela inicial

                            //fijar el valor maximo con el numero de registros a insertar en la barra de progreso
                            bar.Value = 0;
                            bar.Maximum = exlRange.Rows.Count - 3;

                            PROYECTO project = new PROYECTO();
                            form = new FORMULARIO();
                            string bloque = "" + (exlRange.Cells[3, posBloque] as excel.Range).Value + ""; // obtenemos el numero o nombre del bloque inicial
                            project = pyBl.GetProjectByPlace(bloque); // obtenermos el proyecto que tiene asociado ese bloque
                            FormBL FBl = new FormBL(Program.ContextData); //Creamos el BL del formulario
                            int numParcelas = 0; // operador que se utiliza para contabilizar cuantas parcelas tiene asociadas el proyecto

                            for (int i = 3; i <= exlRange.Rows.Count; i++)
                            {
                                //obtenemos los datos correspodientes a linea de inventario y formulario
                                string numPar = "" + (exlRange.Cells[i, posParcela] as excel.Range).Value + ""; //obtenemos el numero de la parcela
                                string nomEst = "" + (exlRange.Cells[i, posStratum] as excel.Range).Value + ""; //obtenermos el nombre del estrato
                                string numBloque = "" + (exlRange.Cells[i, posBloque] as excel.Range).Value + ""; //obtenermos obtenemos el numero de bloque

                                //stratum.DESCRIPESTRATO = "" + (exlRange.Cells[i, posStratum] as excel.Range).Value + "";
                                stratum = new ESTRATO(); // creamos una instancia de estrato
                                stratum = stratumBl.GetStratumByDescription(nomEst); // fijamos el estrato obtenido de la base de datos con el nomEst

                                //sql1 = "INSERT INTO FORMULARIO ( NROFORMULARIO, NROUSUARIO, NROPROY, FECHACREACION, LINEA, CODEST, PARCELA) VALUES ( NEWID()," +user.NROUSUARIO+"," +project.NROPROY+"," +  +","+linea+",";
                                //Validamos si estamos en el mismo bloque esto para si se cambio de bloque o proyecto guardarle a este el numero de parcelas, intensidad de muestreo
                                // y superficie muestreada, al igual que abrir el siguiente proyecto con el valor del bloque
                                if (!bloque.Equals(numBloque))
                                {
                                    bloque = numBloque; // fijamos la operador bloque en el  bloque en el que se esta ahora
                                    project.SUPMUE = numParcelas * project.TAMANO;
                                    project.INTMUE = (project.SUPMUE / project.SUPTOT) * 100;
                                    pyBl.UpdateProject(project);
                                    string result = pyBl.SaveChanges();
                                    if (!result.Equals(""))
                                    {
                                        Error_Form errorForm = new Error_Form(result);
                                        ToolStrip menu = bar.GetCurrentParent();
                                        Principal_Form parent = (Principal_Form)menu.Parent;
                                        errorForm.MdiParent = (Form)parent;
                                        errorForm.Show();
                                        return;
                                    }
                                    numParcelas = 0;
                                    project = pyBl.GetProjectByPlace(bloque);
                                }
                                //stratum = Program.ContextData.ESTRATO.;
                                if (stratum == null && nomEst != "" && nomEst != "Estrato simple")
                                {
                                    stratum = new ESTRATO();
                                    stratum.CODEST = (stratumBl.GetStratums()).Count<ESTRATO>() + 1;
                                    stratum.DESCRIPESTRATO = nomEst;
                                    //stratumBl.InsertStratum(stratum);
                                }

                                if (Numparcera != int.Parse(numPar) || i == 3) // se valida si se ha cambiado de numero de parcela esto para crear un nuevo formulario o si se esta en la primera linea para crear el primer formulario
                                {
                                    numParcelas++;
                                    Numparcera = int.Parse(numPar);
                                    form = new FORMULARIO();
                                    form.NROFORMULARIO = Guid.NewGuid();
                                    form.NROUSUARIO = user.NROUSUARIO;
                                    form.NROPROY = project.NROPROY;
                                    form.FECHACREACION = DateTime.Now;
                                    form.LINEA = int.Parse(numBloque);
                                    form.PARCELA = int.Parse(numPar);
                                    if (stratum == null) form.CODEST = null;
                                    else form.CODEST = stratum.CODEST;
                                    //FBl.InsertForm(form);
                                }
                                else
                                { // si esta en la misma parcela ahora hay que validar si el estrato esta en null para crearlo
                                    // se valida si se trata de un estrato diferente en la misma parcela entonces se crea un nuevo formulario con ese estrato
                                    if (project.NOMTIPODISEMUEST == "ES")
                                    {
                                        if (form.CODEST != stratum.CODEST)
                                        {
                                            form = new FORMULARIO();
                                            form.NROFORMULARIO = Guid.NewGuid();
                                            form.NROUSUARIO = user.NROUSUARIO;
                                            form.NROPROY = project.NROPROY;
                                            form.FECHACREACION = DateTime.Now;
                                            form.LINEA = int.Parse(numBloque);
                                            form.PARCELA = int.Parse(numPar);
                                            if (stratum == null) form.CODEST = null;
                                            else form.CODEST = stratum.CODEST;
                                            //FBl.InsertForm(form);
                                        }
                                    }
                                }

                                project.FORMULARIO.Add(form);// asociammos el formulario a el proyecto

                                if (project.NOMTIPODISEMUEST == "ES")
                                {
                                    //Se va asociar el estrato a la lista de estratos del proyecto, validando si este estrato ya se encuentra en la lista entonces no hace nada si no lo agregamos
                                    if (existStratum(stratum, project) == -1)
                                    {
                                        LISTADODEESTRATOS lS = new LISTADODEESTRATOS();
                                        lS.ESTRATO = stratum;
                                        lS.CODEST = stratum.CODEST;
                                        lS.NROPROY = project.NROPROY;
                                        lS.PROYECTO = project;
                                        lS.PESO = this.returnweight(stratum.DESCRIPESTRATO,3); // se lee el excel para saber cual es el peso para ese estrato en ese proyecto
                                        project.LISTADODEESTRATOS.Add(lS);
                                        if (project.LISTADODEESTRATOS.Count >= 2) // cambiamos el tipo de diseño si se tiene  en la lista de estratos 2 o mas
                                        {
                                            project.NOMTIPODISEMUEST = "ES";
                                        }
                                        //pyBl.UpdateProject(project);
                                    }
                                }
                                // se debe cargar el codigo de la especie por eso se leen los datos de nombre cientifico y comun

                                string familia = "" + (exlRange.Cells[i, posFam] as excel.Range).Value + "";
                                string nomCom = "" + (exlRange.Cells[i, posNomCom] as excel.Range).Value + "";
                                string nomCien = "" + (exlRange.Cells[i, posNomCien] as excel.Range).Value + "";

                                specie = new ESPECIE();
                                //se busca la especie por nombre cientifico y nombre comun si no se encuentra una especie se crea con los valores
                                specie = specieBl.GetSpecieByComNameAndScienName(nomCom, nomCien);
                                if (specie == null)
                                {
                                    specie = new ESPECIE();
                                    specie.CODESP = Guid.NewGuid();
                                    //specie.DIAMMINCORTE = 0;
                                    specie.FAMILIA = familia;
                                    specie.GRUPOCOM = "SV";
                                    specie.NOMCIENTIFICO = nomCien;
                                    specie.NOMCOMUN = nomCom;
                                    //specieBl.InsertSpecie(specie);
                                }
                                //Se verifica el listado de las especies asociadas a el proyecto si la especie ya esta en la list no se hace nada si no esta se agrega
                                if (!project.ESPECIE.Contains(specie))
                                {
                                    project.ESPECIE.Add(specie);
                                    //pyBl.UpdateProject(project);// se manda a actualizar el proyecto porque se modifico la lista de especies
                                }
                                //Se van a cargar los datos de la linea de inventario
                                string numArb = "" + (exlRange.Cells[i, posNumArb] as excel.Range).Value + "";
                                LINEAINVENTARIO lineInv = new LINEAINVENTARIO();
                                lineInv.LINEAINV = Guid.NewGuid();
                                lineInv.NROFORMULARIO = form.NROFORMULARIO;
                                lineInv.CODESP = specie.CODESP;
                                lineInv.ESTADO = "AS";

                                int numArbol = -1;
                                bool band = int.TryParse(numArb, out numArbol);
                                if (int.TryParse(numArb, out numArbol))
                                {
                                    lineInv.NROARB = numArbol;
                                    lineInv.TIPOARBOL = "NBF";
                                }
                                else
                                {
                                    int.TryParse(numArb.Remove(numArb.Length - 1), out numArbol);
                                    lineInv.NROARB = numArbol;
                                    lineInv.TIPOARBOL = "BFB";
                                }
                                int j = 8;
                                decimal cap = 0, altCom = 0, altTot = 0;

                                if (Decimal.TryParse(((exlRange.Cells[i, j] as excel.Range).Value + "").Replace(".", ","), out cap)) lineInv.CAP = cap;
                                if (Decimal.TryParse(((exlRange.Cells[i, j + 1] as excel.Range).Value + "").Replace(".", ","), out altTot)) lineInv.ALTTOT_M = altTot;
                                if (Decimal.TryParse(((exlRange.Cells[i, j + 2] as excel.Range).Value + "").Replace(".", ","), out altCom)) lineInv.ALTCOMER_M = altCom;
                                QualityBL quality = new QualityBL(Program.ContextData);
                                lineInv.CODCALIDAD = (quality.getQualityByDescription("Regular")).CODCALIDAD; // si no se especifica la calidad se la coloca por defecto en regular,

                                if (("" + (exlRange.Cells[i, j + 3] as excel.Range).Value + "").Equals("x")) lineInv.CODCALIDAD = (quality.getQualityByDescription("Bueno")).CODCALIDAD; //si la calidad es buena
                                else
                                    if (("" + (exlRange.Cells[i, j + 5] as excel.Range).Value + "").Equals("x")) lineInv.CODCALIDAD = (quality.getQualityByDescription("Malo")).CODCALIDAD;//si la calidad es mala

                                if (("" + (exlRange.Cells[i, j + 6] as excel.Range).Value + "").Equals("x"))   //si la una linea maderable y el uso pertenece a alimenticia
                                {
                                    LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                                    NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                                    TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                                    lineInvNM.LINEANMAD = Guid.NewGuid();
                                    lineInvNM.NROFORMULARIO = form.NROPROY;
                                    lineInvNM.OBSERVACIONES = "" + (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                                    form.LINEANOMADERABLES.Add(lineInvNM);
                                    lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("AL"));
                                    form.LINEANOMADERABLES.Add(lineInvNM);
                                    //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                                    //formBl.UpdateForm(form);
                                }
                                else
                                {
                                    if (("" + (exlRange.Cells[i, j + 7] as excel.Range).Value + "").Equals("x")) //si la una linea maderable y el uso pertenece a artesanal
                                    {
                                        LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                                        NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                                        TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                                        lineInvNM.LINEANMAD = Guid.NewGuid();
                                        lineInvNM.NROFORMULARIO = form.NROPROY;
                                        lineInvNM.OBSERVACIONES = (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                                        form.LINEANOMADERABLES.Add(lineInvNM);
                                        lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("AR"));
                                        form.LINEANOMADERABLES.Add(lineInvNM);
                                        //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                                        //formBl.UpdateForm(form);
                                    }
                                    else
                                    {
                                        if (("" + (exlRange.Cells[i, j + 8] as excel.Range).Value + "").Equals("x"))  //si la una linea maderable y el uso pertenece a medicinal
                                        {
                                            LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                                            NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                                            TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                                            lineInvNM.LINEANMAD = Guid.NewGuid();
                                            lineInvNM.NROFORMULARIO = form.NROPROY;
                                            lineInvNM.OBSERVACIONES = (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                                            form.LINEANOMADERABLES.Add(lineInvNM);
                                            lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("MD"));
                                            form.LINEANOMADERABLES.Add(lineInvNM);
                                            //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                                            //formBl.UpdateForm(form);
                                        }
                                    }
                                }

                                lineInv.DAP = lineInv.CAP / Convert.ToDecimal(Math.PI);
                                lineInv.AREABASAL = (lineInv.DAP * lineInv.DAP) * (Convert.ToDecimal(Math.PI) / 4);
                                lineInv.VOLTOT = (lineInv.ALTTOT_M * lineInv.AREABASAL * project.FACTORDEFORMA);
                                lineInv.VOLCOM = (lineInv.ALTCOMER_M * lineInv.AREABASAL * project.FACTORDEFORMA);
                                form.LINEAINVENTARIO.Add(lineInv);

                                string result1 = lineInvBl.SaveChanges();
                                if (!result1.Equals(""))
                                {
                                    Error_Form errorForm = new Error_Form(result1);
                                    ToolStrip menu = bar.GetCurrentParent();
                                    Principal_Form parent = (Principal_Form)menu.Parent;
                                    errorForm.MdiParent = (Form)parent;
                                    errorForm.Show();
                                    return;
                                }
                                //lineInvBl.InsertInventoryLine(lineInv);
                                //lineInvBl.SaveChanges();
                                bar.Increment(1);

                                //sql = "INSERT INTO LINEAINVENTARIO ( LINEAINV, NROFORMULARIO, CODCALIDAD, ESTADO, CODESP, NROARB, ALTCOMER_M, ALTTOT_M, AREABASAL, VOLCOM, VOLTOT, CAP, DAP, TIPOARBOL) VALUES ( NEWID(), '";
                            }
                            if (numParcelas > 0)
                            {
                                project.SUPMUE = numParcelas * project.TAMANO;
                                project.INTMUE = (project.SUPMUE / project.SUPTOT) * 100;
                                pyBl.UpdateProject(project);
                                string result = pyBl.SaveChanges();
                                if (!result.Equals(""))
                                {
                                    Error_Form errorForm = new Error_Form(result);
                                    ToolStrip menu = bar.GetCurrentParent();
                                    Principal_Form parent = (Principal_Form)menu.Parent;
                                    errorForm.MdiParent = (Form)parent;
                                    errorForm.Show();
                                    return;
                                }
                                numParcelas = 0;
                            }
                            MessageBox.Show("Los datos se importaron correctamente", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            bar.Visible = false;
                            //cerramos el libro y la aplicacion
                            libros_trabajo.Close();
                            aplicacion.Quit();
                        }
                        bar.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        bar.Visible = false;
                        Error_Form errorForm = new Error_Form(ex.Message);
                        ToolStrip menu = bar.GetCurrentParent();
                        Principal_Form parent = (Principal_Form)menu.Parent;
                        errorForm.MdiParent = (Form)parent;
                        errorForm.Show();
                    }

                }
                else MessageBox.Show("Ningun usuario ha iniciado sesion. Por favor inicie session.", "Operacion invalida", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                bar.Visible = false;
                Error_Form errorForm = new Error_Form(ex.Message);
                ToolStrip menu = bar.GetCurrentParent();
                Principal_Form parent = (Principal_Form)menu.Parent;
                errorForm.MdiParent = (Form)parent;
                errorForm.Show();
            }
        }
        private void guardarLineaBtn_Click(object sender, EventArgs e)
        {
            try
            {
                PROYECTO p = (PROYECTO)Program.Cache.Get("project");
                LINEAINVENTARIO newLine = new LINEAINVENTARIO();
                LINEAINVENTARIO currentLine = (LINEAINVENTARIO)lineaInvBS.Current;
                FORMULARIO f = form.GetForm(newForm.NROFORMULARIO);

                bool error = false;

                if (especieCbx.SelectedItem == null)
                {
                    controladorErrores.SetError(especieCbx, "Seleccione una especie.");
                    error = true;
                }
                if (estadoCbx.SelectedItem == null)
                {
                    controladorErrores.SetError(estadoCbx, "Seleccione una estado sanitario.");
                    error = true;
                }
                if (calidadCbx.SelectedItem == null)
                {
                    controladorErrores.SetError(calidadCbx, "Asocie una calidad al arbol.");
                    error = true;
                }
                if (decimal.Parse(nroArbolTxt.Text) < 1)
                {
                    controladorErrores.SetError(nroArbolTxt, "El numero de arbol debe ser mayor que cero.");
                    error = true;
                }
                if (decimal.Parse(alturaComercialTxt.Text) < 0)
                {
                    controladorErrores.SetError(alturaComercialTxt, "La altura comercial del arbol debe ser mayor que cero.");
                    error = true;
                }
                if (decimal.Parse(alturaTotalTxt.Text) < 0)
                {
                    controladorErrores.SetError(alturaTotalTxt, "La altura total del arbol debe ser mayor que cero.");
                    error = true;
                }
                if (decimal.Parse(cAPDAPTxt.Text) < 0)
                {
                    controladorErrores.SetError(cAPDAPTxt, "El valor de la circufernecia de arbol debe ser mayor o igual a cero.");
                    error = true;
                }
                if (error) return;

                controladorErrores.Clear();

                if (currentLine.LINEAINV == Guid.Empty)
                {
                    newLine.LINEAINV = Guid.NewGuid();
                    newLine.FORMULARIO = f;
                    newLine.ESPECIE = (ESPECIE)especieCbx.SelectedItem;
                    newLine.CALIDAD = (CALIDAD)calidadCbx.SelectedItem;
                    newLine.ESTADOSANITARIO = (ESTADOSANITARIO)estadoCbx.SelectedItem;
                    newLine.NROARB = int.Parse(nroArbolTxt.Text);
                    newLine.TIPOARBOL = ((KeyValuePair<string, string>)tipoArbolCbx.SelectedItem).Key;
                    newLine.ALTCOMER_M = decimal.Parse(alturaComercialTxt.Text);
                    newLine.ALTTOT_M = decimal.Parse(alturaTotalTxt.Text);
                    newLine.CAP = CAPRbtn.Checked ? decimal.Parse(cAPDAPTxt.Text) : (decimal)Math.Round(decimal.Parse(cAPDAPTxt.Text) * (decimal)Math.PI, 3);
                    newLine.DAP = DAPRbtn.Checked ? decimal.Parse(cAPDAPTxt.Text) : (decimal)Math.Round(decimal.Parse(cAPDAPTxt.Text) / (decimal)Math.PI, 3);
                    newLine.AREABASAL = Math.Round((decimal)(ForestCalculatorHelper.BasalAreaCAP((double)newLine.CAP)),3);
                    Dictionary<string, double> valores = new Dictionary<string, double>();
                    valores.Add("H", (double)newLine.ALTTOT_M);
                    valores.Add("FF", (double)p.FACTORDEFORMA);
                    valores.Add("AB", (double)newLine.AREABASAL);
                    Evaluador_Expressiones evaluador= new Evaluador_Expressiones();
                    AleTermResult val = evaluador.EvaluarExpresion(p.FORMULA.EXPRESION, valores, ParentForm);
                    valores["DAP"]=(double)newLine.ALTCOMER_M;
                    val = evaluador.EvaluarExpresion(p.FORMULA.EXPRESION, valores, ParentForm);
                    newLine.VOLCOM = Math.Round((decimal)(ForestCalculatorHelper.TreeVolumeByBasalArea((double)newLine.AREABASAL, (double)newLine.ALTCOMER_M, (double)p.FACTORDEFORMA)),3);
                    newLine.VOLTOT = Math.Round((decimal)(ForestCalculatorHelper.TreeVolumeByBasalArea((double)newLine.AREABASAL, (double)newLine.ALTTOT_M, (double)p.FACTORDEFORMA)),3);
                    lineInv.InsertInventoryLine(newLine);
                    f = form.GetForm(newForm.NROFORMULARIO);
                    string resultSaveChangues = lineInv.SaveChanges();
                    if (resultSaveChangues == "")
                    {
                        lineaInvBS.DataSource = f.LINEAINVENTARIO.ToList();
                        lineaInvBN.Refresh();
                        MessageBox.Show("Los datos fueron almacenados de manera exitosa.", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        lineaInvBS.AddNew();
                        especieCbx.SelectedItem = newLine.ESPECIE;
                        if (newLine.TIPOARBOL == "BFB")
                        {
                            nroArbolTxt.Text = newLine.NROARB.ToString();
                            alturaComercialTxt.Text = newLine.ALTCOMER_M.ToString();
                            alturaTotalTxt.Text = newLine.ALTTOT_M.ToString();
                            tipoArbolCbx.SelectedValue = "BFB";
                        }
                        else tipoArbolCbx.SelectedValue = "NBF";
                    }
                    else
                    {
                        Error_Form errorForm = new Error_Form(resultSaveChangues);
                        errorForm.MdiParent = ParentForm;
                        errorForm.Show();
                    }
                }
                else
                {
                    currentLine.ESPECIE = (ESPECIE)especieCbx.SelectedItem;
                    currentLine.CALIDAD = (CALIDAD)calidadCbx.SelectedItem;
                    currentLine.ESTADOSANITARIO = (ESTADOSANITARIO)estadoCbx.SelectedItem;
                    currentLine.NROARB = int.Parse(nroArbolTxt.Text);
                    currentLine.TIPOARBOL = ((KeyValuePair<string, string>)tipoArbolCbx.SelectedItem).Key;
                    currentLine.ALTCOMER_M = decimal.Parse(alturaComercialTxt.Text);
                    currentLine.ALTTOT_M = decimal.Parse(alturaTotalTxt.Text);
                    newLine.CAP = CAPRbtn.Checked ? decimal.Parse(cAPDAPTxt.Text) : (decimal)Math.Round(decimal.Parse(cAPDAPTxt.Text) * (decimal)Math.PI, 3);
                    newLine.DAP = DAPRbtn.Checked ? decimal.Parse(cAPDAPTxt.Text) : (decimal)Math.Round(decimal.Parse(cAPDAPTxt.Text) / (decimal)Math.PI, 3);
                    currentLine.AREABASAL = (decimal)(ForestCalculatorHelper.BasalAreaDAP((double)newLine.DAP));
                    currentLine.VOLCOM = (decimal)(ForestCalculatorHelper.TreeVolumeByBasalArea((double)newLine.AREABASAL, (double)newLine.ALTCOMER_M, (double)p.FACTORDEFORMA));
                    currentLine.VOLTOT = (decimal)(ForestCalculatorHelper.TreeVolumeByBasalArea((double)newLine.AREABASAL, (double)newLine.ALTTOT_M, (double)p.FACTORDEFORMA));
                    lineInv.UpdateInventoryLine(currentLine);
                    f = form.GetForm(newForm.NROFORMULARIO);
                    string resultSaveChangues = lineInv.SaveChanges();
                    if (resultSaveChangues == "")
                    {
                        lineaInvBS.DataSource = f.LINEAINVENTARIO.ToList();
                        lineaInvBN.Refresh();
                        MessageBox.Show("Los datos fueron actualizados de manera exitosa.", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        Error_Form errorForm = new Error_Form(resultSaveChangues);
                        errorForm.MdiParent = ParentForm;
                        errorForm.Show();
                    }
                }
                modified = true;
                PROYECTO result = project.GetProject(newForm.PROYECTO.NROPROY);
                Program.Cache.Add("project", result, new CacheItemPolicy());
            }
            catch (Exception ex)
            {
                Error_Form errorForm = new Error_Form(ex.Message);
                errorForm.MdiParent = ParentForm;
                errorForm.Show();
            }
        }
Exemplo n.º 3
0
        private void loadInventoryData(ToolStripProgressBar bar, int p)
        {
            bar.Visible = true;
            //recorremos el archivo para leer las lineas de inventario que estan en el libro
            hojas_trabajo = (excel.Worksheet)libros_trabajo.Worksheets.get_Item(p);

            //Definimos el el rango de celdas que seran leidas
            exlRange = hojas_trabajo.UsedRange;

            int posStratum = 0, posNomCom = 0, posFam = 0, posNomCien = 0, posParcela = 0, posCodCal = 0, posNumArb = 0;
            //Recorremos el archivo excel como si fuera una matriz
            string sValor = "";
            posStratum = 1;
            posParcela = 2;
            posNumArb = 3;
            posNomCom = 4;
            posNomCien = 5;
            posFam = 6;
            posCodCal = 10;
            sValor = "" + (exlRange.Cells[3, posParcela] as excel.Range).Value + "";
            int NumParcela = int.Parse(sValor); // se obtiene el numero de la parcela inicial

            //fijar el valor maximo con el numero de registros a insertar en la barra de progreso
            bar.Value = 0;
            bar.Maximum = exlRange.Rows.Count - 2;

            form = new FORMULARIO();
            FormBL FBl = new FormBL(Program.ContextData); //Creamos el BL del formulario
            InventoryLineBL lineInvBl = new InventoryLineBL(Program.ContextData);
            int numParcelas = 0; // operador que se utiliza para contabilizar cuantas parcelas tiene asociadas el proyecto

            for (int i = 3; i <= exlRange.Rows.Count; i++)
            {
                //obtenemos los datos correspodientes a linea de inventario y formulario
                string numPar = "" + (exlRange.Cells[i, posParcela] as excel.Range).Value + ""; //obtenemos el numero de la parcela
                string nomEst = "" + (exlRange.Cells[i, posStratum] as excel.Range).Value + ""; //obtenermos el nombre del estrato

                //stratum.DESCRIPESTRATO = "" + (exlRange.Cells[i, posStratum] as excel.Range).Value + "";
                stratum = new ESTRATO(); // creamos una instancia de estrato
                stratum = stratumBl.GetStratumByDescription(nomEst); // fijamos el estrato obtenido de la base de datos con el nomEst

                //sql1 = "INSERT INTO FORMULARIO ( NROFORMULARIO, NROUSUARIO, NROPROY, FECHACREACION, LINEA, CODEST, PARCELA) VALUES ( NEWID()," +user.NROUSUARIO+"," +project.NROPROY+"," +  +","+linea+",";
                //Validamos si estamos en el mismo bloque esto para si se cambio de bloque o proyecto guardarle a este el numero de parcelas, intensidad de muestreo
                // y superficie muestreada, al igual que abrir el siguiente proyecto con el valor del bloque
                //stratum = Program.ContextData.ESTRATO.;
                if (stratum == null && nomEst != "" && nomEst != "Estrato simple")
                {
                    stratum = new ESTRATO();
                    stratum.CODEST = (stratumBl.GetStratums()).Count<ESTRATO>() + 1;
                    stratum.DESCRIPESTRATO = nomEst;
                    //stratumBl.InsertStratum(stratum);
                }

                if (NumParcela != int.Parse(numPar) || i == 3) // se valida si se ha cambiado de numero de parcela esto para crear un nuevo formulario o si se esta en la primera linea para crear el primer formulario
                {
                    numParcelas++;
                    NumParcela = int.Parse(numPar);
                    form = new FORMULARIO();
                    form.NROFORMULARIO = Guid.NewGuid();
                    form.NROUSUARIO = user.NROUSUARIO;
                    form.NROPROY = newProject.NROPROY;
                    form.FECHACREACION = DateTime.Now;
                    form.LINEA = NumParcela;
                    form.PARCELA = int.Parse(numPar);
                    if (stratum == null) form.CODEST = null;
                    else form.CODEST = stratum.CODEST;
                }
                else
                { // si esta en la misma parcela ahora hay que validar si el estrato esta en null para crearlo
                    // se valida si se trata de un estrato diferente en la misma parcela entonces se crea un nuevo formulario con ese estrato
                    if (newProject.NOMTIPODISEMUEST == "ES")
                    {
                        if (form.CODEST != stratum.CODEST)
                        {
                            form = new FORMULARIO();
                            form.NROFORMULARIO = Guid.NewGuid();
                            form.NROUSUARIO = user.NROUSUARIO;
                            form.NROPROY = newProject.NROPROY;
                            form.FECHACREACION = DateTime.Now;
                            form.LINEA = NumParcela;
                            form.PARCELA = int.Parse(numPar);
                            if (stratum == null) form.CODEST = null;
                            else form.CODEST = stratum.CODEST;
                        }
                    }
                }
                newProject.FORMULARIO.Add(form);// asociammos el formulario a el proyecto

                if (newProject.NOMTIPODISEMUEST == "ES")
                {
                    //Se va asociar el estrato a la lista de estratos del proyecto, validando si este estrato ya se encuentra en la lista entonces no hace nada si no lo agregamos
                    if (existStratum(stratum, newProject) == -1)
                    {
                        LISTADODEESTRATOS lS = new LISTADODEESTRATOS();
                        lS.ESTRATO = stratum;
                        lS.CODEST = stratum.CODEST;
                        lS.NROPROY = newProject.NROPROY;
                        lS.PROYECTO = newProject;
                        lS.TAMANOMUESTRA = this.returnweight(stratum.DESCRIPESTRATO, 3); // se lee el excel para saber cual es el peso para ese estrato en ese proyecto
                        newProject.LISTADODEESTRATOS.Add(lS);
                        if (newProject.LISTADODEESTRATOS.Count > 1) // cambiamos el tipo de diseño si se tiene  en la lista de estratos 2 o mas
                        {
                            newProject.NOMTIPODISEMUEST = "ES";
                        }
                        //pyBl.UpdateProject(project);
                    }
                }
                // se debe cargar el codigo de la especie por eso se leen los datos de nombre cientifico y comun

                string familia = "" + (exlRange.Cells[i, posFam] as excel.Range).Value + "";
                string nomCom = "" + (exlRange.Cells[i, posNomCom] as excel.Range).Value + "";
                string nomCien = "" + (exlRange.Cells[i, posNomCien] as excel.Range).Value + "";

                specie = new ESPECIE();
                //se busca la especie por nombre cientifico y nombre comun si no se encuentra una especie se crea con los valores
                specie = specieBl.GetSpecieByComNameAndScienName(nomCom, nomCien);
                if (specie == null)
                {
                    specie = new ESPECIE();
                    specie.CODESP = Guid.NewGuid();
                    //specie.DIAMMINCORTE = 0;
                    specie.FAMILIA = familia;
                    specie.GRUPOCOM = "SV";
                    specie.NOMCIENTIFICO = nomCien;
                    specie.NOMCOMUN = nomCom;
                    //specieBl.InsertSpecie(specie);
                }
                //Se verifica el listado de las especies asociadas a el proyecto si la especie ya esta en la list no se hace nada si no esta se agrega
                if (!newProject.ESPECIE.Contains(specie))
                {
                    newProject.ESPECIE.Add(specie);
                    //pyBl.UpdateProject(project);// se manda a actualizar el proyecto porque se modifico la lista de especies
                }
                //Se van a cargar los datos de la linea de inventario
                string numArb = "" + (exlRange.Cells[i, posNumArb] as excel.Range).Value + "";
                LINEAINVENTARIO lineInv = new LINEAINVENTARIO();
                lineInv.LINEAINV = Guid.NewGuid();
                lineInv.NROFORMULARIO = form.NROFORMULARIO;
                lineInv.CODESP = specie.CODESP;
                lineInv.ESTADO = "AS";

                int numArbol = -1;
                bool band = int.TryParse(numArb, out numArbol);
                if (int.TryParse(numArb, out numArbol))
                {
                    lineInv.NROARB = numArbol;
                    lineInv.TIPOARBOL = "NBF";
                }
                else
                {
                    int.TryParse(numArb.Remove(numArb.Length - 1), out numArbol);
                    lineInv.NROARB = numArbol;
                    lineInv.TIPOARBOL = "BFB";
                }
                int j = 7;
                decimal cap = 0, altCom = 0, altTot = 0;

                if (Decimal.TryParse(((exlRange.Cells[i, j] as excel.Range).Value + "").Replace(".", ","), out cap)) lineInv.CAP = cap;
                if (Decimal.TryParse(((exlRange.Cells[i, j + 1] as excel.Range).Value + "").Replace(".", ","), out altTot)) lineInv.ALTTOT_M = altTot;
                if (Decimal.TryParse(((exlRange.Cells[i, j + 2] as excel.Range).Value + "").Replace(".", ","), out altCom)) lineInv.ALTCOMER_M = altCom;
                QualityBL quality = new QualityBL(Program.ContextData);
                lineInv.CODCALIDAD = (quality.getQualityByDescription("Regular")).CODCALIDAD; // si no se especifica la calidad se la coloca por defecto en regular,

                if (("" + (exlRange.Cells[i, j + 3] as excel.Range).Value + "").Equals("x")) lineInv.CODCALIDAD = (quality.getQualityByDescription("Bueno")).CODCALIDAD; //si la calidad es buena
                else
                    if (("" + (exlRange.Cells[i, j + 5] as excel.Range).Value + "").Equals("x")) lineInv.CODCALIDAD = (quality.getQualityByDescription("Malo")).CODCALIDAD;//si la calidad es mala

                if (("" + (exlRange.Cells[i, j + 6] as excel.Range).Value + "").Equals("x"))   //si la una linea maderable y el uso pertenece a alimenticia
                {
                    LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                    NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                    TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                    lineInvNM.LINEANMAD = Guid.NewGuid();
                    lineInvNM.NROFORMULARIO = form.NROPROY;
                    lineInvNM.OBSERVACIONES = "" + (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                    form.LINEANOMADERABLES.Add(lineInvNM);
                    lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("AL"));
                    form.LINEANOMADERABLES.Add(lineInvNM);
                    //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                    //formBl.UpdateForm(form);
                }
                else
                {
                    if (("" + (exlRange.Cells[i, j + 7] as excel.Range).Value + "").Equals("x")) //si la una linea maderable y el uso pertenece a artesanal
                    {
                        LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                        NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                        TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                        lineInvNM.LINEANMAD = Guid.NewGuid();
                        lineInvNM.NROFORMULARIO = form.NROPROY;
                        lineInvNM.OBSERVACIONES = (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                        form.LINEANOMADERABLES.Add(lineInvNM);
                        lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("AR"));
                        form.LINEANOMADERABLES.Add(lineInvNM);
                        //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                        //formBl.UpdateForm(form);
                    }
                    else
                    {
                        if (("" + (exlRange.Cells[i, j + 8] as excel.Range).Value + "").Equals("x"))  //si la una linea maderable y el uso pertenece a medicinal
                        {
                            LINEANOMADERABLES lineInvNM = new LINEANOMADERABLES();
                            NonTimberLineBL lineInvNMBl = new NonTimberLineBL(Program.ContextData);
                            TypeUseBL typeUseBl = new TypeUseBL(Program.ContextData);
                            lineInvNM.LINEANMAD = Guid.NewGuid();
                            lineInvNM.NROFORMULARIO = form.NROPROY;
                            lineInvNM.OBSERVACIONES = (exlRange.Cells[i, j + 9] as excel.Range).Value + "";
                            form.LINEANOMADERABLES.Add(lineInvNM);
                            lineInvNM.TIPODEUSO.Add(typeUseBl.GetTypeUse("MD"));
                            form.LINEANOMADERABLES.Add(lineInvNM);
                            //lineInvNMBl.InsertNonTimberLine(lineInvNM);
                            //formBl.UpdateForm(form);
                        }
                    }
                }

                lineInv.DAP = lineInv.CAP / Convert.ToDecimal(Math.PI);
                lineInv.AREABASAL = (lineInv.DAP * lineInv.DAP) * (Convert.ToDecimal(Math.PI) / 4);
                lineInv.VOLTOT = (lineInv.ALTTOT_M * lineInv.AREABASAL * newProject.FACTORDEFORMA);
                lineInv.VOLCOM = (lineInv.ALTCOMER_M * lineInv.AREABASAL * newProject.FACTORDEFORMA);
                form.LINEAINVENTARIO.Add(lineInv);

                string result1 = lineInvBl.SaveChanges();
                if (!result1.Equals(""))
                {
                    Error_Form errorForm = new Error_Form(result1);
                    ToolStrip menu = bar.GetCurrentParent();
                    Principal_Form parent = (Principal_Form)menu.Parent;
                    errorForm.MdiParent = (Form)parent;
                    errorForm.Show();
                    return;
                }
                //lineInvBl.InsertInventoryLine(lineInv);
                //lineInvBl.SaveChanges();
                bar.Increment(1);
            }
            if (numParcelas > 0)
            {
                newProject.SUPMUE = numParcelas * newProject.TAMANO;
                newProject.INTMUE = (newProject.SUPMUE / newProject.SUPTOT) * 100;
                pyBl.UpdateProject(newProject);
                string result = pyBl.SaveChanges();
                if (!result.Equals(""))
                {
                    Error_Form errorForm = new Error_Form(result);
                    ToolStrip menu = bar.GetCurrentParent();
                    Principal_Form parent = (Principal_Form)menu.Parent;
                    errorForm.MdiParent = (Form)parent;
                    errorForm.Show();
                    return;
                }
                numParcelas = 0;
            }
            MessageBox.Show("Los datos se importaron correctamente", "Operacion exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information);
            bar.Visible = false;
        }